Python 如何使用列的格式字符串显示浮点数的 Pandas DataFrame?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20937538/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:35:45  来源:igfitidea点击:

How to display pandas DataFrame of floats using a format string for columns?

pythonpython-2.7pandasipythondataframe

提问by Jason S

I would like to display a pandas dataframe with a given format using print()and the IPython display(). For example:

我想使用print()IPython显示具有给定格式的 Pandas 数据框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

I would like to somehow coerce this into printing

我想以某种方式将其强制打印

         cost
foo   3.46
bar   4.57
baz   5.68
quux  6.79

without having to modify the data itself or create a copy, just change the way it is displayed.

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

How can I do this?

我怎样才能做到这一点?

采纳答案by unutbu

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  3.46
bar  4.57
baz  5.68
quux 6.79

but this only works if you want everyfloat 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   3.46  123.4567
bar   4.57  234.5678
baz   5.68  345.6789
quux  6.79  456.7890

回答by Chris Moore

If you don't want to modify the dataframe, you could use a custom formatter for that column.

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

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})

yields

产量

        cost
foo  3.46
bar  4.57
baz  5.68
quux 6.79

回答by sedeh

Similar to unutbu above, you could also use applymapas follows:

与上面的 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)

回答by Jason S

As of Pandas 0.17 there is now a styling systemwhich essentially provides formatted views of a DataFrame using Python format strings:

从 Pandas 0.17 开始,现在有一个样式系统,它基本上使用Python 格式字符串提供 DataFrame 的格式化视图:

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

which displays

显示

enter image description here

在此处输入图片说明

This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:

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

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

enter image description here

在此处输入图片说明

However it appears to have some limitations:

但是它似乎有一些限制:

  • Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn't add row/column labels):

    constants.loc[2] = dict(name='bogus', value=123.456)
    constants['comment'] = ['fee','fie','fo']
    constants
    
  • 就地添加新行和/或列似乎会导致样式视图不一致(不添加行/列标签):

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

enter image description here

在此处输入图片说明

which looks ok but:

看起来不错,但是:

C

enter image description here

在此处输入图片说明

  • Formatting works only for values, not index entries:

    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
    
  • 格式化仅适用于值,不适用于索引条目:

    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

在此处输入图片说明

回答by Selah

I like using pandas.apply() with python 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)

Also, it can be easily used with multiple columns...

此外,它可以很容易地与多列一起使用......

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)

回答by Carson

summary:

概括:


    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 0.46  100,000
    1 0.79  200,000

         money   share
    0  100.456  100000
    1  200.789  200000
    """

回答by Vlad Bezden

You can also set locale to your region and set float_format to use a currency format. This will automatically set $ sign for currency in USA.

您还可以将语言环境设置为您所在的地区,并将 float_format 设置为使用货币格式。这将自动为美国的货币设置 $ 符号。

import locale

locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

pd.set_option("float_format", locale.currency)

df = pd.DataFrame(
    [123.4567, 234.5678, 345.6789, 456.7890],
    index=["foo", "bar", "baz", "quux"],
    columns=["cost"],
)
print(df)

        cost
foo  3.46
bar  4.57
baz  5.68
quux 6.79