Search code examples
pythonpandasdataframemulti-index

Parentheses on negative values in a multi-index dataframe pandas


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?


Solution

  • 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