'Creating array with values less than the threshold using Python
I want to pick the minimum in the first row and then select values which are less than this minimum as I scan the succeeding rows. The output should look as below.
import numpy as np
a = np.array([[0.4234101 , 0.73587042, 0.81, 0.83202077, 0.73592897],
[0.45714687, 0.13144797, 0.67110076, 0.70283126, 0.32859529],
[0.30888356, 0.84115786, 0.24648344, 0.4963486 , 0.42780253],
[0.10956774, 0.49696239, 0.17086982, 0.34758674, 0.6332388 ],
[0.69931352, 0.72449178, 0.98831224, 0.20775389, 0.19041985]])
print(a<0.4234101)
The desired output is
array([0.4234101 , 0.13144797, 0.32859529, 0.30888356, 0.24648344,
0.10956774, 0.17086982, 0.34758674, 0.20775389, 0.19041985])
Solution 1:[1]
Try:
print([i for i in a.reshape(-1,) if i<0.42])
or if you want it linked to the first value:
print([i for i in a.reshape(-1,) if i<a.reshape(-1,)[0]])
Solution 2:[2]
One of possible solutions is:
Get the minimum from row 0:
a0min = a[0].min()Get following rows:
a1 = a[1:]Get the result:
result = np.insert(a1[a1 < a0min], 0, a0min)i.e. get the wanted elements from a1 (following rows) and insert the minimum from the initial row at the beginning.
The result is:
array([0.4234101 , 0.13144797, 0.32859529, 0.30888356, 0.24648344,
0.10956774, 0.17086982, 0.34758674, 0.20775389, 0.19041985])
You don't need any explicit iteration over the source array, as it is performed under the hood by Numpy.
Solution 3:[3]
The method you might want is np.nditer() which iterates over the single elements of an multidimensional array
import numpy as np
a = np.array([[0.4234101 , 0.73587042, 0.81, 0.83202077, 0.73592897],
[0.45714687, 0.13144797, 0.67110076, 0.70283126, 0.32859529],
[0.30888356, 0.84115786, 0.24648344, 0.4963486 , 0.42780253],
[0.10956774, 0.49696239, 0.17086982, 0.34758674, 0.6332388 ],
[0.69931352, 0.72449178, 0.98831224, 0.20775389, 0.19041985]])
values = []
min = a[0].min()
for element in np.nditer(a[1:]):
if element < min:
values.append(element.item(0))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kilian |
| Solution 2 | |
| Solution 3 |
