将DataFrame的负号值转换为括号

时间:2020-09-13 11:41:24

标签: python pandas

我已经使用-pd.options.display.float_format ='{:,。0f}'。format

设置了DF号格式。

但是,这将导致显示负值,例如-100,000。我希望该值显示为(100,000)。感谢帮助

1 个答案:

答案 0 :(得分:1)

尝试:

df = pd.DataFrame({"a":[1, -23]})
print(df)
    a
0   1
1 -23

df.astype(str).a.str.replace("^-([0-9]*)", "(\\1)")
0       1
1    (23)
Name: a, dtype: object

注意:您要的只是演示目的。

对于小数,您可以尝试:

df.a.astype(str).str.replace("^-([0-9.]*)", "(\\1)")
0       1.0
1    (23.0)
Name: a, dtype: object

或者,如果您愿意:

df.a.astype(str).str.replace("^-([0-9]+\.[0-9]+)", "(\\1)")
0       1.0
1    (23.0)
Name: a, dtype: object