如何格式化 Pandas 数据框的 IPython html 显示?

2024-01-21

如何格式化 Pandas 数据帧的 IPython html 显示,以便

  1. 数字右对齐
  2. 数字以逗号作为千位分隔符
  3. 大浮点数没有小数位

我明白那个numpy有设施set_printoptions我可以在哪里做:

int_frmt:lambda x : '{:,}'.format(x)
np.set_printoptions(formatter={'int_kind':int_frmt})

对于其他数据类型也是如此。

但当以 html 形式显示数据帧时,IPython 不会选择这些格式选项。我还需要有

pd.set_option('display.notebook_repr_html', True)

但与上面的 1, 2, 3 一样。

Edit:下面是我对 2 和 3 的解决方案(不确定这是最好的方法),但我仍然需要弄清楚如何使数字列右对齐。

from IPython.display import HTML
int_frmt = lambda x: '{:,}'.format(x)
float_frmt = lambda x: '{:,.0f}'.format(x) if x > 1e3 else '{:,.2f}'.format(x)
frmt_map = {np.dtype('int64'):int_frmt, np.dtype('float64'):float_frmt}
frmt = {col:frmt_map[df.dtypes[col]] for col in df.columns if df.dtypes[col] in frmt_map.keys()}
HTML(df.to_html(formatters=frmt))

HTML 接收 html 数据的自定义字符串。没有人禁止你传入带有自定义 CSS 样式的样式标签.dataframe类(其中to_html方法添加到表中)。

因此,最简单的解决方案就是添加一个样式并将其与df.to_html:

style = '<style>.dataframe td { text-align: right; }</style>'
HTML( style + df.to_html( formatters=frmt ) )

但我建议为 DataFrame 定义一个自定义类,因为这将更改笔记本中所有表格的样式(样式为“全局”)。

style = '<style>.right_aligned_df td { text-align: right; }</style>'
HTML(style + df.to_html(formatters=frmt, classes='right_aligned_df'))

您还可以在前面的单元格之一中定义样式,然后只需设置classes的参数to_html method:

# Some cell at the begining of the notebook
In [2]: HTML('''<style>
                    .right_aligned_df td { text-align: right; }
                    .left_aligned_df td { text-align: right; }
                    .pink_df { background-color: pink; }
                </style>''')

...

# Much later in your notebook
In [66]: HTML(df.to_html(classes='pink_df'))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何格式化 Pandas 数据框的 IPython html 显示? 的相关文章

随机推荐