Home > Back-end >  Creating array with values less than the threshold using Python
Creating array with values less than the threshold using Python

Time:02-18

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])

CodePudding user response:

You could index the first row, find its minimum and create a boolean mask to filter a with.

a[a < a[0].min()]

If you want the minimum as part of the final output, then you could concatenate it to the output above:

first_row_min = a[0].min()
np.r_[first_row_min, a[a < first_row_min]]

Output:

array([0.4234101 , 0.13144797, 0.32859529, 0.30888356, 0.24648344,
       0.10956774, 0.17086982, 0.34758674, 0.20775389, 0.19041985])

CodePudding user response:

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]])

CodePudding user response:

One of possible solutions is:

  1. Get the minimum from row 0:

    a0min = a[0].min()
    
  2. Get following rows:

    a1 = a[1:]
    
  3. 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.

CodePudding user response:

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))
  • Related