I would like to select only those indices where value is different than 'Nan' and 0
df = pd.DataFrame({'A':[np.nan,3,0,2],
'B':[0,1,1,2]})
df = np.asarray(df)
df[np.nonzero(df) & ~np.isnan(df)]
array(3,1,1,2,2)
Does anyone know what's wrong with it?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With