1.2 Numpy array
1.2 Numpy array
• Fixed Size: Arrays have a fixed size, while lists can dynamically grow.
• Homogeneous Data: Arrays require uniform data types; lists can store mixed types.
1. Axis: The Axis of an array describes the order of the indexing into the array.
Axis 0 = one dimensional Axis 1 = Two dimensional Axis 2 = Three dimensional
2. Shape: The number of elements along with each axis. It is from a tuple.
3. Rank: The rank of an array is simply the number of axes (or dimensions) it has.
Rank1= 1 dimension, Rank2 = 2 Dimension Rank3 = 3 Dimension
4. Data type objects (dtype): It describes how the bytes in the fixed-size block of
memory corresponding to an array item should be interpreted.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print("Shape:", arr.shape)
print("Dimensions:", arr.ndim)
print("Size:", arr.size)
print("Data type:", arr.dtype)
print("Item size:", arr.itemsize)
Output
Shape: (2, 3)
Dimensions: 2
Size: 6
Data type: int64
Item size: 8
…Array Operations…
These operations allow you to perform element-wise arithmetic or other operations
on entire arrays without the need for explicit loops.
• Element-wise Operations:
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]]) OUTPUT
matrix2 = np.array([[5, 6], [7, 8]])
[[19 22]
print(np.dot(matrix1, matrix2)) [43 50]]
Broadcasting..
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6]) OUTPUT
reshaped_arr = arr.reshape(2, 3) # 2 rows, 3 columns [[1 2 3]
print(reshaped_arr) [4 5 6]]
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]]) OUTPUT
flattened_arr = arr.flatten() [1 2 3 4 5 6]
print(flattened_arr)