More Elegant Way To Do Value Comparison While Preserving Nan In Pandas And Numpy Python
So basically I want 5 > np.nan return np.nan or Nan instead of FALSE In pandas series, here's the code : import pandas as pd import numpy as np a = pd.DataFrame({'x':[1,2,3,4],'
Solution 1:
Only a bit improved/(changed) your solution:
value_comparison = (a["x"]>a["y"])
nan_comparison = a[["x", "y"]].notna().all(axis=1)
#alternative
#nan_comparison = a["x"].notna() & a["y"].notna()
m = value_comparison.where(nan_comparison)
print (m)
0 0.0
1 NaN
2 0.0
3 1.0
dtype: float64
Last is possible convert to nullable boolean
:
m = value_comparison.where(nan_comparison).astype('boolean')
print (m)
0 False
1 <NA>
2 False
3 True
dtype: boolean
Post a Comment for "More Elegant Way To Do Value Comparison While Preserving Nan In Pandas And Numpy Python"