Home > Mobile >  how to get the values of array only if the condition is matched
how to get the values of array only if the condition is matched

Time:06-29

I have two arrays a&b, array a is numerical values. array([27, 28, 29, 21, 17, 15, 19, 22, 18, 23, 24, 25, 30, 26]) array b is categorical vlaues. b=array(['no', 'no', 'yes', 'yes', 'yes', 'no', 'yes', 'no', 'yes', 'yes','yes', 'yes', 'yes', 'no'], dtype=object) . I want to get the values if the condition is yes

import numpy as np 
np.where(b =='yes',a,0)
output: array([ 0,  0, 29, 21, 17,  0, 19,  0, 18, 23, 24, 25, 30,  0])

I want to get only values if yes matched. I can use if condition. but I don't want to.

expected output :

array([29 21 17 19 18 23 24 25 30])

CodePudding user response:

Simply use boolean indexing:

out = a[b=='yes']

output:

array([29, 21, 17, 19, 18, 23, 24, 25, 30])

CodePudding user response:

You can also do it using masked array in numpy.

out_ma = np.ma.array(a, b[b=="no"])
out_ma.nonzero()

Output:

array([29, 21, 17, 19, 18, 23, 24, 25, 30])
  • Related