你能格式化 Pandas 整数来显示,比如用于浮点数的 `pd.options.display.float_format` 吗?

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

Can you format pandas integers for display, like `pd.options.display.float_format` for floats?

pythonpandasformattingnumber-formatting

提问by Michael K

I've seen thisand thison formatting floating-pointnumbers for display in pandas, but I'm interested in doing the same thing for integers.

我已经看到这个这个关于格式化浮点数以在Pandas中显示,但我有兴趣对integers做同样的事情。

Right now, I have:

现在,我有:

pd.options.display.float_format = '{:,.2f}'.format

That works on the floats in my data, but will either leave annoying trailing zeroes on integers that are cast to floats, or I'll have plain integers that don't get formatted with commas.

这适用于我的数据中的浮点数,但要么会在转换为浮点数的整数上留下烦人的尾随零,要么我将使用未用逗号格式化的纯整数。

The pandas docs mention a SeriesFormatterclass about which I haven't been able to find any information.

pandas 文档提到了一个SeriesFormatter我无法找到任何信息的课程。

Alternatively, if there's a way to write a single string formatter that will format floats as '{:,.2f}'and floats with zero trailing decimal as '{:,d}', that'd work too.

或者,如果有一种方法可以编写一个单一的字符串格式化程序,将浮点数格式化为,'{:,.2f}'并将浮点数以零尾随十进制数设置为'{:,d}',那也行。

采纳答案by unutbu

You could monkey-patch pandas.io.formats.format.IntArrayFormatter:

你可以猴子补丁pandas.io.formats.format.IntArrayFormatter

import contextlib
import numpy as np
import pandas as pd
import pandas.io.formats.format as pf
np.random.seed(2015)

@contextlib.contextmanager
def custom_formatting():
    orig_float_format = pd.options.display.float_format
    orig_int_format = pf.IntArrayFormatter

    pd.options.display.float_format = '{:0,.2f}'.format
    class IntArrayFormatter(pf.GenericArrayFormatter):
        def _format_strings(self):
            formatter = self.formatter or '{:,d}'.format
            fmt_values = [formatter(x) for x in self.values]
            return fmt_values
    pf.IntArrayFormatter = IntArrayFormatter
    yield
    pd.options.display.float_format = orig_float_format
    pf.IntArrayFormatter = orig_int_format


df = pd.DataFrame(np.random.randint(10000, size=(5,3)), columns=list('ABC'))
df['D'] = np.random.random(df.shape[0])*10000

with custom_formatting():
    print(df)

yields

产量

      A     B     C        D
0 2,658 2,828 4,540 8,961.77
1 9,506 2,734 9,805 2,221.86
2 3,765 4,152 4,583 2,011.82
3 5,244 5,395 7,485 8,656.08
4 9,107 6,033 5,998 2,942.53

while outside of the with-statement:

在 之外时with-statement

print(df)

yields

产量

      A     B     C            D
0  2658  2828  4540  8961.765260
1  9506  2734  9805  2221.864779
2  3765  4152  4583  2011.823701
3  5244  5395  7485  8656.075610
4  9107  6033  5998  2942.530551