当前位置: 首页 > 面试题库 >

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

陈哲
2023-03-14
问题内容

我已经看到了这个有关格式 的浮点
对大pandas显示的数字,但我有兴趣做同样的事情为 整数

现在,我有:

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

这对我的数据中的浮点数有效,但会在转换为浮点数的整数上留下令人讨厌的尾随零,或者我将拥有不使用逗号格式化的普通整数。

熊猫文档提到了一个SeriesFormatter我无法找到任何信息的类。

另外,如果有一种方法可以编写单个字符串格式化程序,该格式化程序会将float格式化为,并将'{:,.2f}'尾随零的浮点数格式化为'{:,d}',则也可以。


问题答案:

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


 类似资料:
  • 问题内容: 如何设置熊猫数据帧的IPython html显示格式,以便 数字是正确的 数字以逗号作为千位分隔符 大花车没有小数位 据我所知,有设施,我可以这样做: 对于其他数据类型也是如此。 但是在以html显示数据框时,IPython不会选择这些格式选项。我仍然需要 但上面有1,2,3。 编辑: 以下是我针对2和3的解决方案(不确定这是最好的方法),但是我仍然需要弄清楚如何使数字列正确。 问题答

  • 主要内容:get_option(),set_option(),reset_option(),describe_option(),option_context(),常用参数项在用 Pandas 做数据分析的过程中,总需要打印数据分析的结果,如果数据体量较大就会存在输出内容不全(部分内容省略)或者换行错误等问题。Pandas 为了解决上述问题,允许你对数据显示格式进行设置。下面列出了五个用来设置显示格式的函数,分别是: get_option() set_option() reset_option()

  • 问题内容: 如何利用System.out.print(ln/f)一种方式将我的输出格式化为表格? 如果要使用printf,我应该指定哪种格式来获得以下结果? 我要打印的示例表: ``` n result1 result2 time1 time2 5 1000.00 20000.0 1000ms 1250ms 5 1000.00 20000.0 1000ms 1250ms 5 1000.00 200

  • 问题内容: 我的python脚本中有一个数字,希望用作matplotlib中图形标题的一部分。是否有将浮点数转换为格式化的TeX字符串的函数? 基本上, 退货 但是我想要 或至少让matplotlib格式化浮点格式,就像格式化第二个字符串一样。我也一直使用python 2.4,因此特别喜欢在旧版本中运行的代码。 问题答案: 您可以执行以下操作: 在旧样式中:

  • 问题内容: 我有一个类型的变量,我需要以不超过3个小数的精度打印它,但是它不应该有任何结尾的零… 例如。我需要 我尝试使用,我做错了吗? 谢谢。:) 问题答案: 尝试使用模式代替: 输出: