大熊猫DataFrame中的自定义浮动格式

spl*_*ter 3 python formatting dataframe python-3.x pandas

我有一个DataFrame

   0       1
0  3.000   5.600
1  1.200   3.456
Run Code Online (Sandbox Code Playgroud)

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

   0    1
0  3    5.6
1  1.2  3.456
Run Code Online (Sandbox Code Playgroud)

什么是达到此目的的优雅方法(不会在的条目上无效循环DataFrame)?

或许更笼统地说:是否有一种方法可以设置pandas为始终这样做?例如pandas选项之一?

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

小智 14

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

pd.set_option('display.precision', 2)
Run Code Online (Sandbox Code Playgroud)

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


Max*_*axU 6

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
Run Code Online (Sandbox Code Playgroud)

更新:

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
Run Code Online (Sandbox Code Playgroud)

注意:请注意,.applymap()方法的速度非常慢,因为它对map(func, series)DataFrame中的每个系列都这样做


Sim*_*mas 5

一个使用 round() 的简单方法,将要舍入的位数作为参数传递。

假设您的 DataFrame 名为“df”:

df.round(2)
Run Code Online (Sandbox Code Playgroud)

输出:

   0     1
0  3.00  5.60
1  1.20  3.45
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用。它不会对数字进行四舍五入。 (2认同)