我有一个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
像上面我指出的那样在各个条目之间有所不同。
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()方法的速度非常慢,因为它对map(func, series)
DataFrame中的每个系列都这样做
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句