如何使用列的格式字符串显示浮动的pandas数据帧?

2024-03-29 01:44:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用print()和IPythondisplay()显示具有给定格式的pandas数据帧。例如:

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

无需修改数据本身或创建副本,只需更改其显示方式即可。

我该怎么做?


Tags: columns数据dataframepandasdfindexfoo格式
3条回答

如果不想修改数据框,可以为该列使用自定义格式化程序。

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.to_string(formatters={'cost':'${:,.2f}'.format})

收益率

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

As of Pandas 0.17 there is now a styling system它实际上使用Python format strings提供数据帧的格式化视图:

import pandas as pd
import numpy as np

constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C

显示

enter image description here

这是一个视图对象;数据帧本身不会更改格式,但数据帧中的更新会反映在视图中:

constants.name = ['pie','eek']
C

enter image description here

但是,它似乎有一些限制:

  • 在适当位置添加新行和/或列似乎会导致样式化视图中的不一致(不添加行/列标签):

    constants.loc[2] = dict(name='bogus', value=123.456)
    constants['comment'] = ['fee','fie','fo']
    constants
    

enter image description here

看起来不错,但是:

C

enter image description here

  • 格式化仅适用于值,而不适用于索引项:

    constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
    constants.set_index('name',inplace=True)
    C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
    C
    

enter image description here

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

但这只在您希望每个float都用美元符号格式化时才有效。

否则,如果您只想对某些浮动设置美元格式,那么我认为您必须预先修改数据帧(将这些浮动转换为字符串):

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

相关问题 更多 >