Table of Contents
ToggleIn 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.
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.
In the following example, we are retrieving the shape of a NumPy array using the shape attribute −
# Open Compiler import numpy as np a = np.array([[1,2,3],[4,5,6]]) print (a.shape)
Output:
Following is the output obtained −
(2, 3)
Here, we are resizing an array using the shape attribute in NumPy −
# Open Compiler import numpy as np a = np.array([[1,2,3],[4,5,6]]) a.shape = (3,2) print (a)
Output:
This will produce the following result −
[[1, 2]
[3, 4]
[5, 6]]
NumPy also provides a reshape() function to resize an array −
# Open Compiler import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = a.reshape(3,2) print (b)
Output:
Following is the output of the above code −
[[1, 2]
[3, 4]
[5, 6]]
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.
In this example, we are creating a NumPy array a with “24” evenly spaced integers from “0” to “23” using the arange() function −
# Open Compiler import numpy as np a = np.arange(24) print (a)
Output:
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]
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
Output:
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]]]
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.
In the example below, we are using the “size” attribute in NumPy to retrieve the size of a 3D array −
# Open Compiler
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)
Output:
Following is the output obtained −
3D Array:
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]
Size of the array: 12
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.
In this example, we are specifying the data type of a NumPy array at the time of its creation using the “dtype” attribute −
# Open Compiler
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)
Output:
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
The itemsize attribute returns the length of each element of the 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.
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)
Output:
We get the output as shown below −
1
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)
Output:
The result produced is as follows −
4
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.
In this example, we are using the “nbytes” attribute to retrieve the total memory used by the array’s data buffer −
# Open Compiler
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")
Output:
The output obtained is as shown below −
Total memory size of the array: 20 bytes
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.
In the example below, we are accessing an element in a 2D array using the “strides” attribute to calculate the memory address −
# Open Compiler
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)
Output:
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: (16, 4)
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 |
The following example shows the current values of array’s flags −
# Open Compiler import numpy as np x = np.array([1,2,3,4,5]) print (x.flags)
Output:
Following is the output obtained −
C_CONTIGUOUS : True
F_CONTIGUOUS : True
OWNDATA : True
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
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.
In this example, view_array is a view into original_array, and the base attribute of view_array points to original_array −
# Open Compiler
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)
Output:
The result produced is as follows −
Base array of view_array: [[1 2 3]
[4 5 6]]
For arrays with complex numbers, the real and imag attributes return the real and imaginary parts, respectively.
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 −
# Open Compiler
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)
Output:
We get the output as shown below −
Real part: [1. 3. 5.]
Imaginary part: [2. 4. 6.]
Following is the list of various Array attributes in NumPy −
| Sr.No. | Operation & Description |
|---|---|
| 1 | ndarray.ndimThis attribute returns the number of dimensions in the array. |
| 2 | ndarray.shapeThis attribute returns the size of the array in each dimension. |
| 3 | ndarray.sizeThis attribute returns number of elements in the array. |
| 4 | ndarray.dtypeThis attribute returns the datatype of elements in the array. |
| 5 | ndarray.itemsizeThis returns the size of each element in the array. |
| 6 | ndarray.nbytesThis returns the total bytes consumed by the array elements. |
| 7 | ndarray.TReturns the view of the transposed array. |
| 8 | ndarray.realReturns the real part of the array. |
| 9 | ndarray.imagReturns the imaginary part of the array. |
| 10 | ndarray.flat1D array iterator over the array. |
| 11 | ndarray.ctypesThis returns an object to simplify the interaction of the array with the ctypes module. |
| 12 | ndarray.dataThis returns the buffer containing the actual elements of the array in the memory. |
Key Takeaway: Master NumPy array attributes effectively at Vista Academy!
