-1

I want to add a "+" to all positive values in my df.

Here is my df

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':[-1,3,0,5],
                   'B':[4,5,6,5],
                   'C':[8,-9,np.nan,7]})

print (df)
   A  B    C
0 -1  4  8.0
1  3  5 -9.0
2  0  6  NaN
3  5  5  7.0

This is what I want it to look like:

print (df)
   A  B    C
0 -1  +4  +8.0
1  +3  +5 -9.0
2  +0  +6  NaN
3  +5  +5  +7.0

My attempt:

df[df > 0] = "+"

That just replaced the positive values with "+"

Boosted_d16
  • 13,340
  • 35
  • 98
  • 158

2 Answers2

6

Use display options instead of converting your floats as strings (which is NOT what you want) :

Example :

import pandas as pd
pd.options.display.float_format = '{:+,.2f}'.format
pd.DataFrame({'a': [1.2, -3.4]})

Returns :

    a
0   +1.20
1   -3.40

EDIT

Better solution imo : you can use this to change the format of one or multiple columns of your dataframe

Example :

import pandas as pd
df = pd.DataFrame({'a': [1, -3], 'b': ['Hello', 'World'], 'c': [1.234, -1.3]})
df.style.format({'a':'{:+d}', 'c': '{:+g}'})

Returns :

    a   b       c
0   +1  Hello   +1.234
1   -3  World   -1.3

For your specific dataframe, you can do :

df.style.format('{:+g}')

Returns

     A  B   C
0   -1  +4  +8
1   +3  +5  -9
2   +0  +6  +nan
3   +5  +5  +7

If you want to remove the +nan, you can do :

df.style.format(lambda x:  'NaN' if np.isnan(x) else '{:+g}'.format(x))

Returns

     A   B   C
0   -1  +4  +8
1   +3  +5  -9
2   +0  +6  NaN
3   +5  +5  +7
Corentin Limier
  • 4,946
  • 1
  • 13
  • 24
4
df = df.applymap(lambda x: "+"+str(x) if x>0 else x)
print(df)

Output:

    A   B     C
0  -1  +4  +8.0
1  +3  +5    -9
2   0  +6   NaN
3  +5  +5  +7.0
Srce Cde
  • 1,764
  • 10
  • 15