NumPy - Array Attributes
NumPy Array Attributes
In NumPy, attributes are properties of array objects that provide important information about the arrays and their data. These attributes are used to access various details regarding the structure and configuration of the arrays without modifying them.
In this chapter, we will discuss the various array attributes of NumPy.
NumPy Shape Attribute
The NumPy shape attribute provides the dimensions of the array. It returns a tuple representing the size of the array along each dimension. It can also be used to resize the array.
Example 1
In the following example, we are retrieving the shape of a NumPy array using the shape attribute −
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
print (a.shape)
Following is the output obtained −
(2, 3)
Example 2
Here, we are resizing an array using the shape attribute in NumPy −
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a.shape = (3,2)
print (a)
This will produce the following result −
[[1, 2]
[3, 4]
[5, 6]]
Example 3
NumPy also provides a reshape() function to resize an array −
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = a.reshape(3,2)
print (b)
Following is the output of the above code −
[[1, 2]
[3, 4]
[5, 6]]
NumPy Dimensions Attribute
The ndim attribute returns the number of dimensions (axes) of the array.
In NumPy, the dimension of an array is known as its rank. Each axis in a NumPy array corresponds to a dimension. The number of axes (dimensions) is referred to as the array’s rank.
Arrays can be of any dimension, from one-dimensional (1D) arrays (also known as vectors) to multi-dimensional arrays like 2D arrays (matrices) or even higher-dimensional arrays.
Example 1
In this example, we are creating a NumPy array a with “24” evenly spaced integers from “0” to “23” using the arange() function −
import numpy as np
a = np.arange(24)
print (a)
The output obtained is as shown below −
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
Example 2
Here, we are creating a one-dimensional NumPy array a with “24” elements using the arange() function and then reshaping it into a three-dimensional array “b” with the shape provided, resulting in a 3D array −
# This is one dimensional array
import numpy as np
a = np.arange(24)
a.ndim
# Now reshape it
b = a.reshape(2,4,3)
print (b)
# b is having three dimensions
After executing the above code, we get the following output −
[[[ 0, 1, 2]
[ 3, 4, 5]
[ 6, 7, 8]
[ 9, 10, 11]]
[[12, 13, 14]
[15, 16, 17]
[18, 19, 20]
[21, 22, 23]]]
NumPy Size Attribute
The size attribute returns the total number of elements in the array. In NumPy, the size of an array refers to the total number of elements contained within the array.
- For a one-dimensional array, the size is simply the number of elements.
- For a two-dimensional array, the size is the product of the number of rows and columns.
- For a three-dimensional array, the size is the product of the sizes of all three dimensions.
Example
In the example below, we are using the “size” attribute in NumPy to retrieve the size of a 3D arrray −
import numpy as np
# Creating a 3D array
array_3d = np.array([[[1, 2, 3], [4, 5, 6]],
[[7, 8, 9], [10, 11, 12]]])
print("3D Array:\n", array_3d)
print("Size of the array:", array_3d.size)
Following is the output obtained −
3D Array:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
Size of the array: 12
NumPy Data Type Attribute
The dtype attribute describes the data type of the elements in the array. In NumPy, the data type of an array refers to the type of the elements stored in the array.
NumPy supports a wide range of data types, including integers, floats, complex numbers, booleans, and more. Each data type is represented by a dtype object. The “dtype” not only specifies the type of the data but also its size and byte order.
Example
In this example, we are specifying the data type of a NumPy array at the time of its creation using the “dtype” attribute −
import numpy as np
# Creating an array of integers
int_array = np.array([1, 2, 3], dtype=np.int32)
print("Integer Array:", int_array)
print("Data type of int_array:", int_array.dtype)
# Creating an array of floats
float_array = np.array([1.1, 2.2, 3.3], dtype=np.float64)
print("Float Array:", float_array)
print("Data type of float_array:", float_array.dtype)
# Creating an array of complex numbers
complex_array = np.array([1 + 2j, 3 + 4j], dtype=np.complex128)
print("Complex Array:", complex_array)
print("Data type of complex_array:", complex_array.dtype)
This will produce the following result −
Integer Array: [1 2 3]
Data type of int_array: int32
Float Array: [1.1 2.2 3.3]
Data type of float_array: float64
Complex Array: [1.+2.j 3.+4.j]
Data type of complex_array: complex128
NumPy Itemsize Attribute
The itemsize attribute returns the the length of each element of array in bytes.
The item size is determined by the data type (dtype) of the array. Different data types require different amounts of memory. For example, an int32 type requires “4” bytes per element, while a float64 type requires “8” bytes per element.
Example 1
In the following example, we are checking the item size for an array of integer data type “int8” −
# dtype of array is int8 (1 byte)
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.int8)
print (x.itemsize)
We get the output as shown below −
1
Example 2
Now, we are checking the item size for an array of float data type “float32” −
# dtype of array is now float32 (4 bytes)
import numpy as np
x = np.array([1,2,3,4,5], dtype = np.float32)
print (x.itemsize)
The result produced is as follows −
4
NumPy Buffer Information Attribute
The nbytes attribute returns the total number of bytes consumed by the elements of the array.
In NumPy, the buffer information of an array provides details about the underlying memory structure that stores the array data. This includes information on the memory layout, the data type, and the byte offset within the buffer.
Example
In this example, we are using the “nbytes” attribute to retrieve the total memory used by the array’s data buffer −
import numpy as np
# Creating an array
array = np.array([1, 2, 3, 4, 5], dtype=np.int32)
# Checking total memory size of the array
print("Total memory size of the array:", array.nbytes, "bytes")
The output obtained is as shown below −
Total memory size of the array: 20 bytes
NumPy Strides Attribute
The strides attribute provides the number of bytes to step in each dimension when traversing an array.
Strides specify the number of bytes that must be skipped in memory to move from one element to the next along each axis. They help in determining how the array is laid out in memory and how to access elements.
Example
In the example below, we are accessing an element in a 2D array using “strides” attribute to calculate the memory address −
import numpy as np
# Creating a 2D array
array = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# Checking the strides
print("Array shape:", array.shape)
print("Array strides:", array.strides)
The stride for the first axis (rows) is 16 bytes, which means to move from one row to the next, NumPy skips 16 bytes in memory. The stride for the second axis (columns) is 4 bytes, indicating that to move from one column to the next within the same row, NumPy skips 4 bytes −
Array shape: (3, 4)
Array strides: (32, 8)
NumPy Flags Attribute
The flags attribute returns information about the memory layout of the array, such as whether it is contiguous in memory.
NumPy provides several flags that describe different aspects of the array’s memory layout and properties −
Sr.No. | Attribute & Description |
---|---|
1 | **C_CONTIGUOUS (C)**The data is in a single, C-style contiguous segment |
2 | **F_CONTIGUOUS (F)**The data is in a single, Fortran-style contiguous segment |
3 | **OWNDATA (O)**The array owns the memory it uses or borrows it from another object |
4 | **WRITEABLE (W)**The data area can be written to. Setting this to False locks the data, making it read-only |
5 | **ALIGNED (A)**The data and all elements are aligned appropriately for the hardware |
6 | **UPDATEIFCOPY (U)**This array is a copy of some other array. When this array is deallocated, the base array will be updated with the contents of this array |
Example
The following example shows the current values of array’s flags −
import numpy as np
x = np.array([1,2,3,4,5])
print (x.flags)
Following is the output obtained −
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
NumPy Base Attribute
The base attribute returns the base object if the array is a view on another array. If the array owns its data, base is “None”. In NumPy, the concept of “array base” refers to the original array from which a new array is derived.
Example
In this example, “view_array” is a view into “original_array”, and the base attribute of “view_array” points to “original_array” −
import numpy as np
# Creating an array
original_array = np.array([[1, 2, 3], [4, 5, 6]])
# Creating a view (a slice) of the original array
view_array = original_array[0:1, :]
# Checking the base of the view
print("Base array of view_array:", view_array.base)
The result produced is as follows −
Base array of view_array: [[1 2 3]
[4 5 6]]
NumPy Real and Imaginary Parts Attribute
For arrays with complex numbers, the real and imag attributes return the real and imaginary parts, respectively.
Example
In this example, we are using the “real” attribute to return an array with the real parts and “imag” attribute to return an array with the imaginary parts −
import numpy as np
# Creating an array of complex numbers
complex_array = np.array([1+2j, 3+4j, 5+6j])
# Accessing the real part
real_part = complex_array.real
print("Real part:", real_part)
# Accessing the imaginary part
imaginary_part = complex_array.imag
print("Imaginary part:", imaginary_part)
We get the output as shown below −
Real part: [1. 3. 5.]
Imaginary part: [2. 4. 6.]