how to filter 1d numpy array values based on condition
- User
how to filter 1d numpy array values based on condition
Assistant
To filter a 1D NumPy array based on a condition, you can use boolean indexing:
pythonimport numpy as np # Create a sample array arr = np.array([1, 5, 3, 8, 2, 7, 4, 9]) # Filter values greater than 4 filtered = arr[arr > 4] print(filtered) # Output: [5 8 7 9] # Multiple conditions (values between 3 and 7) filtered = arr[(arr >= 3) & (arr <= 7)] print(filtered) # Output: [5 3 7 4] # Using a function def is_even(x): return x % 2 == 0 filtered = arr[np.vectorize(is_even)(arr)] print(filtered) # Output: [8 2 4] # Where and astype method filtered = arr[np.where(arr > 5)] print(filtered) # Output: [8 7 9]Would you like me to explain or break down this code?
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.