Python Pandas DataFrame 中的自定义浮点格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42735541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Customized float formatting in a pandas DataFrame
提问by splinter
I have a DataFrame
:
我有一个DataFrame
:
0 1
0 3.000 5.600
1 1.200 3.456
and for presentation purposes I would like it to be converted to
出于演示目的,我希望将其转换为
0 1
0 3 5.6
1 1.2 3.456
What is the elegant way to achieve this (without looping inefficiently over entries of the DataFrame
)?
实现此目的的优雅方法是什么(不会在 的条目上低效循环DataFrame
)?
Or perhaps more generally: is there a way to set pandas
up such that it is always doing this? E.g. one of the pandas
options?
或者更一般地说:有没有办法设置pandas
它总是这样做?例如其中一种pandas
选择?
Notice that pd.options.display.float_format = '{:,.0f}'.format
will not work, as it would give a fixed number of decimals, rather than having it vary across entries of the DataFrame
as I indicated above.
请注意,这pd.options.display.float_format = '{:,.0f}'.format
将不起作用,因为它会给出固定的小数位数,而不是DataFrame
像我上面指出的那样在 的条目之间变化。
回答by MaxU
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
UPDATE:
更新:
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
NOTE:be aware that .applymap()method is pretty slow as it's doing map(func, series)
for each series in the DataFrame
注意:请注意.applymap()方法非常慢,因为它对map(func, series)
DataFrame 中的每个系列都执行
回答by Simas
a simple method using round(), pass the number of digits you want to round to as a parameter.
一个使用 round() 的简单方法,将要舍入的位数作为参数传递。
Assuming that your DataFrame is named 'df':
假设您的 DataFrame 名为“df”:
df.round(2)
output:
输出:
0 1
0 3.00 5.60
1 1.20 3.45
回答by SEDaradji
A good solution for this to test whether the value has a decimal part and format it accordingly :
一个很好的解决方案来测试该值是否有小数部分并相应地对其进行格式化:
pd.options.display.float_format = lambda x : '{:.0f}'.format(x) if int(x) == x else '{:,.2f}'.format(x)
Edit: This will produce an error when NaNs are in your data. Consider instead using round():
pd.options.display.float_format = lambda x : '{:.0f}'.format(x) if round(x,0) == x else '{:,.2f}'.format(x)
编辑:当您的数据中包含 NaN 时,这将产生错误。考虑使用round():
pd.options.display.float_format = lambda x : '{:.0f}'.format(x) if round(x,0) == x else '{:,.2f}'.format(x)