In NumPy, searching means finding specific elements or their positions inside an array. NumPy provides functions such as where(), searchsorted(), and nonzero() to search for values based on different conditions. These functions are useful when finding employee records, product prices, student marks, and specific values in large datasets.
1. What is Array Searching in NumPy?
Array searching helps you find the position of a particular value or identify elements that match a condition.
The where() function is commonly used to find the indexes of elements that satisfy a condition.
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
result = np.where(arr == 30)
print(result)
Output:
(array([2]),)
Explanation:
arr == 30checks which element is equal to 30.np.where()returns the index of the matching element.- The index is
2because NumPy indexing starts from 0.
2. Search for Multiple Matching Values Using where()
If a value appears more than once in an array, where() returns the indexes of all matching elements.
Example:
import numpy as np
marks = np.array([75, 80, 75, 90, 85, 75])
result = np.where(marks == 75)
print(result)
Output:
(array([0, 2, 5]),)
Explanation:
The value 75 appears at indexes 0, 2, and 5. The where() function returns all three positions.
3. Search Using Greater Than and Less Than Conditions
You can use comparison operators with where() to find elements that satisfy a condition.
Example:
import numpy as np
marks = np.array([45, 60, 75, 85, 95])
result = np.where(marks > 75)
print(result)
Output:
(array([3, 4]),)
Explanation:
marks > 75checks which marks are greater than 75.- The matching values are
85and95. - Their indexes are
3and4.
4. Get Matching Values Using where()
The where() function returns indexes, not the actual matching values. You can use those indexes to retrieve the values from the original array.
Example:
import numpy as np
sales = np.array([10000, 15000, 20000, 25000, 30000])
indexes = np.where(sales >= 20000)
result = sales[indexes]
print("Indexes:", indexes)
print("Matching Sales:", result)
Output:
Indexes: (array([2, 3, 4]),)
Matching Sales: [20000 25000 30000]
Explanation:
where()finds the indexes of sales values greater than or equal to 20,000.sales[indexes]retrieves the matching values.
5. Search Using Multiple Conditions
You can combine conditions using & (AND) and | (OR) inside where().
Always put each condition inside parentheses.
Example: Using AND
import numpy as np
marks = np.array([45, 60, 75, 85, 95])
result = np.where((marks >= 60) & (marks <= 85))
print(result)
Output:
(array([1, 2, 3]),)
Explanation:
- The first condition checks marks greater than or equal to 60.
- The second condition checks marks less than or equal to 85.
&requires both conditions to be true.- The matching values are
60,75, and85.
6. Search Using searchsorted()
The searchsorted() function finds the position where a new value should be inserted in a sorted array to maintain its sorted order.
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
result = np.searchsorted(arr, 35)
print(result)
Output:
3
Explanation:
- The array is already sorted.
- The value
35should be inserted between30and40. - Its insertion position is index
3.
Important: The searchsorted() function assumes the input array is sorted. It returns an insertion position, not necessarily the index of an existing matching value.
7. Search Multiple Values Using NumPy searchsorted()
You can search for multiple insertion positions by passing a list or array of values.
Example:
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
result = np.searchsorted(arr, [15, 25, 45])
print(result)
Output:
[1 2 4]
Explanation:
15should be inserted at index1.25should be inserted at index2.45should be inserted at index4.
8. Use side Parameter in searchsorted()
The side parameter controls where a value should be inserted when duplicate values are present.
It supports two options:
side="left"returns the first suitable insertion position.side="right"returns the position after existing equal values.
Example:
import numpy as np
arr = np.array([10, 20, 20, 20, 30, 40])
left = np.searchsorted(arr, 20, side="left")
right = np.searchsorted(arr, 20, side="right")
print("Left Position:", left)
print("Right Position:", right)
Output:
Left Position: 1
Right Position: 4
Explanation:
- The first occurrence of
20is at index1. - The position after the last occurrence of
20is index4.
9. Search Non-Zero Elements Using nonzero()
The nonzero() function returns the indexes of elements that are not equal to zero.
Example:
import numpy as np
arr = np.array([0, 10, 0, 20, 30, 0])
result = np.nonzero(arr)
print(result)
Output:
(array([1, 3, 4]),)
Explanation:
- Zero values are ignored.
- The non-zero values are
10,20, and30. - Their indexes are
1,3, and4.
10. Search Non-Zero Elements in a 2-D Array
You can also use nonzero() with a multi-dimensional array. It returns a separate index array for each dimension.
Example:
import numpy as np
arr = np.array([
[0, 10, 0],
[20, 0, 30]
])
result = np.nonzero(arr)
print(result)
Output:
(array([0, 1, 1]), array([1, 0, 2]))
Explanation:
The output contains two arrays:
- The first array represents row indexes.
- The second array represents column indexes.
The non-zero elements are located at (0, 1), (1, 0), and (1, 2).
11. Difference Between NumPy Search Functions
| Function | Purpose |
|---|---|
where() | Finds indexes of elements matching a condition |
searchsorted() | Finds insertion positions in a sorted array |
nonzero() | Finds indexes of non-zero elements |
Student Task
A teacher stores the marks of students in a NumPy array.
import numpy as np
marks = np.array([45, 75, 60, 90, 75, 85, 50, 95])
Complete these tasks:
- Find the indexes of students who scored
75. - Find the indexes of students who scored more than
80. - Find the actual marks greater than or equal to
90. - Find the indexes of students whose marks are between
60and85. - Create a sorted array and use NumPy
searchsorted()to find the insertion position of70. - Use NumPy
nonzero()to find the indexes of non-zero elements in a new array.
Final Student Challenge: Company Product Sales Search
A company stores the monthly sales figures of its products. Your task is to search for products based on their sales performance.
import numpy as np
sales = np.array([12000, 18000, 15000, 25000, 18000, 30000, 10000])
# Find indexes where sales equal 18000
equal_sales = np.where(sales == 18000)
# Find indexes where sales are greater than 20000
high_sales = np.where(sales > 20000)
# Get actual sales values greater than 20000
high_sales_values = sales[high_sales]
# Find sales between 15000 and 25000
medium_sales = np.where((sales >= 15000) & (sales <= 25000))
print("Indexes of 18000 Sales:", equal_sales)
print("Indexes of High Sales:", high_sales)
print("High Sales Values:", high_sales_values)
print("Indexes of Medium Sales:", medium_sales)
Expected Output:
Indexes of 18000 Sales: (array([1, 4]),)
Indexes of High Sales: (array([3, 5]),)
High Sales Values: [25000 30000]
Indexes of Medium Sales: (array([1, 2, 3, 4]),)
Your Challenge:
- Find the indexes where sales are exactly
15000. - Find all sales values greater than
18000. - Find the indexes where sales are less than
15000. - Create a sorted sales array and use
searchsorted()to find where22000should be inserted. - Use
nonzero()to find the positions of non-zero sales values.
Key Takeaways
where()finds the indexes of elements that satisfy a condition.- You can use comparison operators such as
==,>,<, and>=withwhere(). - Multiple conditions can be combined using
&and|. - NumPy
searchsorted()finds insertion positions in a sorted array. side="left"andside="right"control insertion positions for duplicate values.- NumPy
nonzero()returns the indexes of non-zero elements. - You can use the returned indexes to retrieve matching values from an array.
Frequently Asked Questions (FAQs)
1. What is NumPy Array Search in Python?
NumPy Array Search is used to find specific elements or values in an array. NumPy provides functions such as where(), searchsorted(), and nonzero() to search for elements based on different conditions.
2. How do you search for an element in a NumPy Array?
You can use the np.where() function to find the index positions of elements that match a specific condition.
Example: np.where(arr == 30)
It returns the index position where the value 30 is found.
3. What is the NumPy searchsorted() function?
The NumPy searchsorted() function finds the index position where a value should be inserted into a sorted array to maintain its sorting order.
Example: np.searchsorted(arr, 25)
4. What is NumPy nonzero() used for?
The NumPy nonzero() function returns the index positions of elements that are not equal to zero in an array. It is useful for identifying non-zero values in numerical datasets.
5. What is the difference between NumPy where() and nonzero()?
The where() function returns the indices of elements that satisfy a specified condition, whereas nonzero() returns the indices of all non-zero elements in an array.
6. Can we search for multiple elements in a NumPy Array?
Yes, you can use NumPy functions such as where() with conditions to search for multiple elements that match specific criteria in an array.
7. Does NumPy searchsorted() work with unsorted arrays?
The searchsorted() function is designed for sorted arrays. If the input array is not sorted, the returned insertion position may not give the expected result.
8. What are some common NumPy Array Search examples?
Common NumPy Array Search examples include finding the index of a specific value using where(), locating non-zero elements using nonzero(), and finding insertion positions using searchsorted(). These methods are useful for searching and analyzing numerical data in Python.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
