Array Attributes
NumPy arrays have several attributes that provide important information about their properties.
# Creating a sample NumPy array
arr = np.array([[10, 20, 30], [40, 50, 60]])
print("Array:\n", arr)
print("Shape of array:", arr.shape)
# Returns (rows, columns)
print("Size of array:", arr.size)
# Returns total number of elements
print("Number of dimensions:", arr.ndim) # Returns 2 (for 2D array)
print("Data type of elements:", arr.dtype) # Data type of elements
print("Item size in bytes:", arr.itemsize) # Size of each element in bytes
print("Total memory consumed:", arr.nbytes, "bytes") # Total memory usage
Key Takeaways:
- .shape tells the (rows, columns) of an array
- .size gives the total number of elements
- .dtype shows the data type of elements
- .ndim returns the number of dimensions
Array Indexing and Slicing
Just like Python lists, NumPy arrays support indexing and slicing.
1. Accessing Elements in a 1D Array
arr_1d = np.array([10, 20, 30, 40, 50])
print("First Element:", arr_1d[0])
# Access first element
print("Last Element:", arr_1d[-1])
# Access last element
print("Elements from index 1 to 3:", arr_1d[1:4]) # Slicing
print("Every second element:", arr_1d[::2]) # Step slicing
2. Accessing Elements in a 2D Array
arr_2d = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
print("Element at row 1, column 2:", arr_2d[1, 2]) # Accessing element
print("First row:", arr_2d[0, :]) # Accessing entire row
print("First column:", arr_2d[:, 0]) # Accessing entire column