Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select indices where value np.nonzero() and ~np.isnan()

I would like to select only those indices where value is different than 'Nan' and 0

Create Dataframe

df = pd.DataFrame({'A':[np.nan,3,0,2],
                   'B':[0,1,1,2]})

df = np.asarray(df)

Unfortunately below code does not work

df[np.nonzero(df) & ~np.isnan(df)]

Expected result

array(3,1,1,2,2)

Does anyone know what's wrong with it?

like image 260
Filip Avatar asked Dec 07 '25 08:12

Filip


1 Answers

Convert values to 1d array by numpy.ravel and then for non 0 values compare by != 0:

a = np.ravel(df.to_numpy())
a = a[(a != 0) & ~np.isnan(a)]
print (a)
[3. 1. 1. 2. 2.]

Like mentioned @sammywemmy, thank you, here np.ravel is not necessary:

a = df.to_numpy()
a = a[(a != 0) & ~np.isnan(a)]
print (a)
[3. 1. 1. 2. 2.]

You cannot compare by numpy.nonzero, because it return indices instead mask:

Return the indices of the elements that are non-zero.

like image 193
jezrael Avatar answered Dec 09 '25 20:12

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!