使用 pandas 样式,使用逗号作为小数点分隔符

Juk*_*uka 2 python pandas pandas-styles

我想使用 pandas 风格,并使用逗号作为小数分隔符。

以此数据框为例:

tb = pd.DataFrame({"Variable": [5, 4.5, 4.8, 4.7], "std_err": [1, .06, .09, .17]}, 
                index = ['Group A', 'Group B', 'Group C', 'Group D'])
Run Code Online (Sandbox Code Playgroud)
多变的 标准错误
A组 5.0 1.00
B组 4.5 0.06
C组 4.8 0.09
D组 4.7 0.17

我试过这个:

locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
pd.set_option("float_format", locale.str)

tb = pd.DataFrame({"Variable": [4.9853, 4.5345, 4.8542, 4.7234], 
                   "std_err": [.9234, .0676, .0917, .1784]}, 
                   index = ['Group A', 'Group B', 'Group C', 'Group D'])
tb.style.bar()
Run Code Online (Sandbox Code Playgroud)

但我希望看到逗号作为小数分隔符和样式栏,而是我得到了一个用样式格式化的表格,但忽略了区域设置。

我可以两者都拥有吗?使用样式(条形、颜色等)和逗号作为小数点分隔符格式化的表格?

Hen*_*ker 5

最直接的修复方法是指定decimal的参数Styler.format

tb.style.format(decimal=',').bar()
Run Code Online (Sandbox Code Playgroud)

小数点格式为逗号和条形

其他替代方案包括将 设置formatter为类似的函数locale.str

locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')

tb.style.format(formatter=locale.str).bar()
Run Code Online (Sandbox Code Playgroud)

使用区域设置字符串格式和栏设置样式的数据框

或者locale.format_str

locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')

tb.style.format(
    formatter=lambda x: locale.format_string('%.6f', x)
).bar()
Run Code Online (Sandbox Code Playgroud)

DataFrame 格式为 6 位小数精度,小数点为逗号,并带有叠加条形图