首页 > 解决方案 > 将 DataFrame 的负号值转换为括号

问题描述

我已经使用 - pd.options.display.float_format='{:,.0f}'.format 设置了 DF 数字格式

但是,这会导致显示负值,例如-100,000。我希望该值显示为 (100,000)。帮助表示赞赏

标签: pythonpandas

解决方案


尝试:

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

推荐阅读