NumPy Array Slicing
Array slicing in NumPy allows you to extract a portion of an array. This feature is essential for analyzing specific parts of datasets, such as historical temperature trends in cities like Coimbatore (Tamil Nadu, India) or Mumbai (Maharashtra, India).
Key Topics
Slicing 1D Arrays
Slicing a 1D array is straightforward: specify a start index, stop index, and optionally, a step. The slice includes elements from the start index up to (but not including) the stop index.
Example
# Slicing a 1D array
import numpy as np
# Temperature data
temperatures = np.array([29, 31, 30, 32, 28, 27])
print("First three days:", temperatures[0:3])
print("Last three days:", temperatures[-3:])
Output
Last three days: [32 28 27]
Explanation: The slice temperatures[0:3]
extracts the first three elements, while temperatures[-3:]
retrieves the last three elements using negative indexing.
Slicing 2D Arrays
Slicing a 2D array involves specifying slices for both rows and columns. This is useful for analyzing tabular data, such as rainfall in Erode (Tamil Nadu, India) and Pune (Maharashtra, India).
Example
# Slicing a 2D array
rainfall = np.array([[120, 110, 130], [90, 100, 80], [150, 140, 160]])
print("First two rows:")
print(rainfall[0:2, :])
print("Last two columns:")
print(rainfall[:, 1:])
Output
[[120 110 130]
[ 90 100 80]]
Last two columns:
[[110 130]
[100 80]
[140 160]]
Explanation: The slice rainfall[0:2, :]
retrieves the first two rows, and rainfall[:, 1:]
retrieves the last two columns.
Slicing with Steps
Slicing with steps allows you to skip elements. This is useful for analyzing alternate days or years, such as visitor data from Kanchipuram (Tamil Nadu, India).
Example
# Slicing with steps
visitor_data = np.array([100, 150, 200, 250, 300, 350])
print("Every second value:", visitor_data[::2])
print("Reverse order:", visitor_data[::-1])
Output
Reverse order: [350 300 250 200 150 100]
Explanation: The slice visitor_data[::2]
selects every second value, and visitor_data[::-1]
reverses the array.
Key Takeaways
- Flexible Slicing: Extract specific portions of arrays using start, stop, and step indices.
- 2D Array Slicing: Retrieve rows, columns, or specific submatrices using slicing techniques.
- Step Slicing: Use steps to skip elements or reverse arrays.
- Real-World Applications: Analyze trends in cities like Coimbatore, Mumbai, Erode, Pune, and Kanchipuram.