【问题标题】:Use pandas style using comma as decimal separator使用以逗号作为小数分隔符的 pandas 样式
【发布时间】:2021-11-04 20:10:57
【问题描述】:

我想使用 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'])
Variable std_err
Group A 5.0 1.00
Group B 4.5 0.06
Group C 4.8 0.09
Group 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()

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

两个都可以吗?使用样式(条形、颜色等)格式化并使用逗号作为小数分隔符的表格?

【问题讨论】:

    标签: python pandas pandas-styles


    【解决方案1】:

    最直接的解决方法是指定Styler.formatdecimal 参数:

    tb.style.format(decimal=',').bar()
    

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

    locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
    
    tb.style.format(formatter=locale.str).bar()
    

    locale.format_str:

    locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
    
    tb.style.format(
        formatter=lambda x: locale.format_string('%.6f', x)
    ).bar()
    

    【讨论】:

    • 非常感谢!实际上,第一个解决方案在这里不起作用......(TypeError:format()得到了一个意外的关键字参数'十进制')另一个做得很好!
    • 是的。 decimal 是“1.3.0 版中的新功能”。但很高兴有一款适合您!
    • 再次感谢!我刚刚升级了我的熊猫。上次使用 conda 更新时它不能正常工作。我用 pip 做到了。
    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2018-10-08
    • 2016-02-10
    • 1970-01-01
    相关资源
    最近更新 更多