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) |
| |
| print("Size of array:", arr.size) |
| |
| print("Number of dimensions:", arr.ndim) |
| print("Data type of elements:", arr.dtype) |
| print("Item size in bytes:", arr.itemsize) |
| print("Total memory consumed:", arr.nbytes, "bytes") |
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]) |
| |
| print("Last Element:", arr_1d[-1]) |
| |
| print("Elements from index 1 to 3:", arr_1d[1:4]) |
| print("Every second element:", arr_1d[::2]) |
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 |