0

I have a multi-index dataframe of the form below():

key  nm    c0    c1   c2   c3  
bar one -0.42  0.56  0.27  1.08
    two -0.67  0.11  1.47  0.52
baz one  0.40  0.57  1.71  1.03
    two -0.37 -1.15 -1.34  0.84

I am trying to set parentheses on the negative numbers, such that it looks like below:

key  nm    c0    c1   c2     c3  
bar one (0.42)  0.56  0.27   1.08
    two (0.67)  0.11  1.47   0.52
baz one  0.40  0.57   1.71   1.03
    two (0.37) (1.15) (1.34)  0.84

I have tried masking it with

idx = pd.IndexSlice
mask = df.loc[idx[:, :], :] < 0

Please help how can I set parentheses on this mask; OR if there is a better way of doing that?

vvv
  • 461
  • 1
  • 5
  • 14
  • Does this answer your question? [Accounting formatting in Pandas df](https://stackoverflow.com/questions/51325640/accounting-formatting-in-pandas-df) – Bernardo Trindade Aug 16 '21 at 16:26

2 Answers2

0

Try with applymap with format , notice here the number became str

df.applymap(lambda x : str(x) if x >= 0 else f'({abs(x)})')
Out[497]: 
         c0      c1      c2    c3
nm                               
one  (0.42)    0.56    0.27  1.08
two  (0.67)    0.11    1.47  0.52
one     0.4    0.57    1.71  1.03
two  (0.37)  (1.15)  (1.34)  0.84
BENY
  • 317,841
  • 20
  • 164
  • 234
0

You can try with where:

df.where(df.ge(0), '('+df.abs().astype(str)+')')
mozway
  • 194,879
  • 13
  • 39
  • 75