Professional Documents
Culture Documents
ch-1 Numpy - 3rd - Day
ch-1 Numpy - 3rd - Day
Searching Arrays
You can search an array for a certain value, and return the indexes that get a match.
Example
Find the indexes where the value is 4:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 4, 4])
x = np.where(arr == 4)
print(x)
Output
(array([3, 5, 6]),)
Example
Find the indexes where the values are even:
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
x = np.where(arr%2 == 0)
print(x)
Output
(array([1, 3, 5, 7]),)
Search Sorted
Example
Find the indexes where the value 7 should be inserted:
import numpy as np
arr = np.array([6, 7, 8, 9])
x = np.searchsorted(arr, 7)
print(x)
Output
1
The method starts the search from the left and returns the first index where the
number 7 is no longer larger than the next value.
NumPy Sorting Arrays
Ordered sequence is any sequence that has an order corresponding to elements, like
numeric or alphabetical, ascending or descending.
The NumPy ndarray object has a function called sort(), that will sort a specified
array.
import numpy as np
arr = np.array([3, 2, 0, 1])
print(np.sort(arr))
Output
[0 1 2 3]
You can also sort arrays of strings, or any other data type:
Example
Sort the array alphabetically:
import numpy as np
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))
Output
['apple' 'banana' 'cherry']
If you use the sort() method on a 2-D array, both arrays will be sorted:
Example
import numpy as np
print(np.sort(arr))
Output
[[2 3 4]
[0 1 5]]
NumPy has a ufunc for this, called add(x, y) that will produce the same result.
Example
import numpy as np
x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
z = np.add(x, y)
print(z)
Output
[ 5 7 9 11]
Example
CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+