NumPy Arrays vs Python Lists
• Fixed Size: Arrays have a fixed size, while lists can dynamically grow.
• Homogeneous Data: Arrays require uniform data types; lists can store mixed types.
• Performance: Arrays are faster due to their optimized implementation.
• Memory Efficiency: Arrays use contiguous memory blocks, unlike lists.
• Element wise operation can possible in NumPy array.
…Attributes Of An Array in NumPy…
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.
• ndarray.shape: Returns a tuple representing the shape (dimensions) of the array.
• ndarray.ndim: Returns the number of dimensions (axes) of the array.
• ndarray.size: Returns the total number of elements in the array.
• ndarray.dtype: Provides the data type of the array elements.
• ndarray.itemsize: Returns the size (in bytes) of each element
…Example…
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 OUTPUT
arr = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6]) • [5 7 9]
• [ 4 10 18]
• [-3 -3 -3]
print(arr + arr2) • [0.25 0.4 0.5 ]
print(arr * arr2)
print(arr - arr2)
print(arr / arr2)
Matrix Operations (Dot product):
• Using Dot method , two matrix can be multiplied.
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..
Broadcasting is a powerful feature in NumPy that allows you to perform operations on
arrays of different shapes.
import numpy as np OUTPUT
arr = np.array([[1, 2], [3, 4]])
[[11 12]
# Adding 10 to each element of the array [13 14]]
print(arr + 10)
…Reshaping and Flattening…
Reshaping: Convert one-dimensional arrays into multi-dimensional arrays.
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]]
Flattening: Convert multi-dimensional arrays into one-dimensional arrays.
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)