我想使用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, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
print(df)
收益率
cost
foo $123.46
bar $234.57
baz $345.68
quux $456.79
但这只在你希望每个浮点数都用美元符号格式化时才有效。
否则,如果你只想为一些浮点数设置美元格式,那么我认为你必须预先修改数据帧(将这些浮点数转换为字符串):
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
简介:
df = pd.DataFrame({'money': [100.456, 200.789], 'share': ['100,000', '200,000']})
print(df)
print(df.to_string(formatters={'money': '${:,.2f}'.format}))
for col_name in ('share',):
df[col_name] = df[col_name].map(lambda p: int(p.replace(',', '')))
print(df)
"""
money share
0 100.456 100,000
1 200.789 200,000
money share
0 $100.46 100,000
1 $200.79 200,000
money share
0 100.456 100000
1 200.789 200000
"""
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
但这只在你希望每个浮点数都用美元符号格式化时才有效。
否则,如果你只想为一些浮点数设置美元格式,那么我认为你必须预先修改数据帧(将这些浮点数转换为字符串):
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
类似于上面的unutbu,你也可以像下面这样使用applymap:
import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
df = df.applymap("${0:.2f}".format)
我喜欢使用pandas.apply()和python format()。
import pandas as pd
s = pd.Series([1.357, 1.489, 2.333333])
make_float = lambda x: "${:,.2f}".format(x)
s.apply(make_float)
此外,它可以很容易地用于多个列…
df = pd.concat([s, s * 2], axis=1)
make_floats = lambda row: "${:,.2f}, ${:,.3f}".format(row[0], row[1])
df.apply(make_floats, axis=1)