Home > database >  Is it possible to clip and fill other value with NAN in pandas?
Is it possible to clip and fill other value with NAN in pandas?

Time:10-18

To keep only the positive values, we can clip a dataframe or a specific column(s) of a dataframe using

df.clip(lower = 0)

But it replaces all negative values with zero. Is it possible to keep only non-negative values and replace all other with Nan?

I looked in this pandas documentation, but fill method is not here.

Another way is to replace all zeros with Nan but it will also convert those values which were actually Zero.

CodePudding user response:

Use DataFrame.mask with DataFrame.lt or DataFrame.le:

print (df)
   a  b  c
0  2 -6  8
1 -5 -8  0

df1 = df.mask(df.lt(0))
print (df1)
     a   b  c
0  2.0 NaN  8
1  NaN NaN  0

df2 = df.mask(df.le(0))
print (df2)
     a   b    c
0  2.0 NaN  8.0
1  NaN NaN  NaN
  • Related