如何使用列的格式字符串显示大 pandas 的数据帧? [英] How to display pandas DataFrame of floats using a format string for columns?
问题描述
我想使用 print()
和IPython display()
。例如:
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
我想以某种方式将其压缩到打印中
cost
foo $ 123.46
bar $ 234.57
baz $ 345.68
quux $ 456.79
而无需修改数据本身或创建副本,只需更改方式
我该怎么做?
import pandas as pd
pd.options.display.float_format ='$ {:,。2f}'。format
df = pd.DataFrame([123.4567,234.5678 ,345.6789,465.7890],
index = ['foo','bar','baz','quux'],
column = ['cost'])
print(df)
yield
cost
foo $ 123.46
bar $ 234.57
baz $ 345.68
quux $ 456.79
但是,只有当您想要每个 float使用美元符号进行格式化时,这才有效。 p>
否则,如果您只想要一些浮点数的美元格式化,那么我想您必须预修改数据框(将这些浮点数转换为字符串):
import pandas as pd
pre>
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
I would like to display a pandas dataframe with a given format using
print()
and the IPythondisplay()
. 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.
How can I do this?
解决方案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)
yields
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)
yields
cost foo foo $123.46 123.4567 bar $234.57 234.5678 baz $345.68 345.6789 quux $456.79 456.7890
这篇关于如何使用列的格式字符串显示大 pandas 的数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!