【问题标题】:Print pandas df with style.format in iPython在 iPython 中使用 style.format 打印 pandas df
【发布时间】:2020-01-02 23:57:50
【问题描述】:

最小的工作示例:

import pandas as pd
df = pd.DataFrame({
    'letters':('A', 'B', 'C'),
    'numbers':(0.1111, 0.2222, 0.3333)
}).set_index('letters')
df.style.format('{:.2f}')

结果:

Out[4]: <pandas.io.formats.style.Styler at 0x7f963f826eb8>

我想要什么:

类似于默认的 Jupyter 输出:

【问题讨论】:

    标签: python pandas jupyter-notebook


    【解决方案1】:

    一种方法是使用df.to_stringformattersfloat_format 关键字

    >>> print(df.to_string(float_format=lambda x: '{:.2f}'.format(x)))
             numbers
    letters         
    A           0.11
    B           0.22
    C           0.33
    

    float_format 将对所有浮点数应用一个函数来格式化,而格式化程序可以接受一个列表或字典来格式化数据框中的特定列。

    【讨论】:

      猜你喜欢
      • 2023-03-04
      • 2015-07-11
      • 2020-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 2014-10-19
      相关资源
      最近更新 更多