Home > Net >  Converting any negative values in pd.dataframe to positive, but the positive values become NaN
Converting any negative values in pd.dataframe to positive, but the positive values become NaN

Time:12-06

I have a pd.dataframe as shown below. For any negative values, i want to add 256 to make it positive. My code works for this part, however the other 2 positive values become NaN and I do not want that. How can I only 256 to negative value and leave the positive numbers unchanged? Many thanks

my pandas dataframe dfx:

red green  blue

0 72 101 -125

'''

dfx = dfx[dfx < 0] 256

current output:

red green   blue

0 NaN NaN 131

desired output:

red green  blue

0 72 101 131

CodePudding user response:

Use DataFrame.mask:

dfx = dfx.mask(dfx < 0, dfx   256 )
print (dfx)
   red  green  blue
0   72    101   131

Your solution should be changed:

dfx[dfx < 0]  = 256
print (dfx)
   red  green  blue
0   72    101   131
  • Related