pandas DataFrame 中的自定义浮点格式

新手上路,请多包涵

我有一个 DataFrame

    0       1
0  3.000   5.600
1  1.200   3.456

出于演示目的,我希望将其转换为

   0    1
0  3    5.6
1  1.2  3.456

实现这一目标的优雅方法是什么(不会低效地循环 DataFrame 的条目)?

或者更一般地说:有没有办法设置 pandas 让它总是这样做?例如 pandas 选项之一?

请注意, pd.options.display.float_format = '{:,.0f}'.format 将不起作用,因为它会给出固定的小数位数,而不是像我上面指出的那样让它在 DataFrame 的条目之间变化。

原文由 splinter 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 507
2 个回答
In [188]: df
Out[188]:
       a      b       c
0 1.0000 2.2460  2.0000
1 3.0000 4.4920  6.0000
2 5.0000 6.7380 10.0000

In [189]: pd.options.display.float_format = '{:,.2f}'.format

In [190]: df.apply(lambda x: x.astype(int) if np.allclose(x, x.astype(int)) else x)
Out[190]:
   a    b   c
0  1 2.25   2
1  3 4.49   6
2  5 6.74  10

更新:

 In [222]: df
Out[222]:
       0      1
0 3.0000 5.6000
1 1.2000 3.4560

In [223]: df.applymap(lambda x: str(int(x)) if abs(x - int(x)) < 1e-6 else str(round(x,2)))
Out[223]:
     0     1
0    3   5.6
1  1.2  3.46

注意: 请注意 .applymap() 方法非常慢,因为它对 DataFrame 中的每个系列执行 map(func, series)

原文由 MaxU - stop genocide of UA 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果有人想要一种快速的方法将相同的精度应用于数据框中的所有数字类型(而不用担心 str 类型):

 pd.set_option('display.precision', 2)

这适用于在 jupyter 笔记本中显示 DataFrame 和 Styler 对象。

原文由 user3826929 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题