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

Problem Description:

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

Solution – 1

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
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject