多索引数据框中负值的括号 pandas

Parentheses on negative values in a multi-index dataframe pandas

我有一个如下形式的多索引数据框():

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

我正在尝试在负数上设置括号,如下所示:

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

我试过用

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

请帮助我如何在这个掩码上设置括号;或者是否有更好的方法?

试试 applymapformat ,注意这里的数字变成了 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

你可以试试 where:

df.where(df.ge(0), '('+df.abs().astype(str)+')')