NumPy Array Search
Searching in NumPy arrays helps locate specific elements or values based on conditions. This is especially useful when analyzing large datasets, such as identifying temperature extremes in cities like Salem (Tamil Nadu, India) or Lucknow (Uttar Pradesh, India).
Key Topics
Searching for a Single Value
The where()
function returns the indices of elements that match a specified value.
Example
# Searching for a single value
import numpy as np
temperatures = np.array([30, 35, 40, 30, 25, 30])
result = np.where(temperatures == 30)
print("Indices where temperature is 30:", result)
Output
Explanation: The where()
function identifies all indices where the value matches 30.
Searching Using Conditions
You can use the where()
function with conditions to locate elements that satisfy specific criteria, such as identifying temperatures above 30 degrees in cities like Madurai (Tamil Nadu, India) or Patna (Bihar, India).
Example
# Searching with conditions
temperatures = np.array([25, 30, 35, 40, 28])
hot_days = np.where(temperatures > 30)
print("Indices of hot days (temperature > 30):", hot_days)
print("Hot temperatures:", temperatures[hot_days])
Output
Hot temperatures: [35 40]
Explanation: The where()
function returns indices where the condition (temperature > 30
) is satisfied. These indices are then used to extract the corresponding temperatures.
Key Takeaways
- Single Value Search: Use
where()
to find indices of specific values. - Conditional Search: Apply conditions to locate elements matching criteria (e.g., greater than, less than).
- Real-World Applications: Identify trends and outliers in datasets from cities like Salem, Lucknow, Madurai, and Patna.