您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

您可以格式化要显示的pandas整数,例如用于浮动的`pd.options.display.float_format`吗?

您可以格式化要显示的pandas整数,例如用于浮动的`pd.options.display.float_format`吗?

您可以猴子补丁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)

产量

      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

在之外时with-statement

print(df)

产量

      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
其他 2022/1/1 18:30:26 有661人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶