Home > Software engineering >  Values based on a criterion
Values based on a criterion

Time:06-12

I have an array P with dimensions (2,3,3). I want to generate an output based on a criterion P<150. The current and desired outputs are attached.

import numpy as np
P = np.array([[[128.22918457, 168.52413295, 209.72343319],
        [129.01598287, 179.03716051, 150.68633749],
        [131.00688309, 187.42601593, 193.68172751]],

       [[ 87.70103267, 115.2603484 , 143.4381863 ],
        [ 88.23915528, 122.45062554, 103.06037156],
        [ 89.60081102, 128.18809696, 132.46662659]]])

print([P<150])

The current output is

array([[[ True, False, False],
        [ True, False, False],
        [ True, False, False]],

       [[ True,  True,  True],
        [ True,  True,  True],
        [ True,  True,  True]]])

The desired output is

array([[[128.22918457,129.01598287,131.00688309]],
        
        [[ 87.70103267, 115.2603484 , 143.4381863 ],
        [ 88.23915528, 122.45062554, 103.06037156],
        [ 89.60081102, 128.18809696, 132.46662659]]])

CodePudding user response:

try this:

filterarr = [P<150]
newarr = P[filterarr]
print(newarr)

source: https://www.w3schools.com/python/numpy/numpy_array_filter.asp

CodePudding user response:

The logic is unclear as your output is not a valid numpy array (you cannot have dimensions with a different number of items).

Not directly what you asked, but assuming you want to flatten the output and keep 3 columns:

P2 = P.ravel()
out = P2[P2<150].reshape(-1,3)

Output:

array([[128.22918457, 129.01598287, 131.00688309],
       [ 87.70103267, 115.2603484 , 143.4381863 ],
       [ 88.23915528, 122.45062554, 103.06037156],
       [ 89.60081102, 128.18809696, 132.46662659]])

CodePudding user response:

You can filter the array by putting the variable when indexing

import numpy as np
P = np.array([[[128.22918457, 168.52413295, 209.72343319],
        [129.01598287, 179.03716051, 150.68633749],
        [131.00688309, 187.42601593, 193.68172751]],

       [[ 87.70103267, 115.2603484 , 143.4381863 ],
        [ 88.23915528, 122.45062554, 103.06037156],
        [ 89.60081102, 128.18809696, 132.46662659]]])
        
# Just add P in the indexing
print(P[P<150])
  • Related