如何使用列的格式字符串显示浮点数的 Pandas DataFrame? [英] How to display pandas DataFrame of floats using a format string for columns?
问题描述
我想使用 print()
和 IPython display()
显示具有给定格式的 Pandas 数据帧.例如:
I would like to display a pandas dataframe with a given format using print()
and the IPython display()
. For example:
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print df
cost
foo 123.4567
bar 234.5678
baz 345.6789
quux 456.7890
我想以某种方式将其强制打印
I would like to somehow coerce this into printing
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
无需修改数据本身或创建副本,只需更改其显示方式即可.
without having to modify the data itself or create a copy, just change the way it is displayed.
我该怎么做?
推荐答案
import pandas as pd
pd.options.display.float_format = '${:,.2f}'.format
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print(df)
收益
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
但这仅适用于每个浮点数都使用美元符号进行格式化的情况.
but this only works if you want every float to be formatted with a dollar sign.
否则,如果您只想为某些浮点数设置美元格式,那么我认为您必须预先修改数据框(将这些浮点数转换为字符串):
Otherwise, if you want dollar formatting for some floats only, then I think you'll have to pre-modify the dataframe (converting those floats to strings):
import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
df['foo'] = df['cost']
df['cost'] = df['cost'].map('${:,.2f}'.format)
print(df)
收益
cost foo
foo $123.46 123.4567
bar $234.57 234.5678
baz $345.68 345.6789
quux $456.79 456.7890
这篇关于如何使用列的格式字符串显示浮点数的 Pandas DataFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!