如何格式化IPandy html显示的Pandas数据帧?

beh*_*uri 29 html python ipython pandas

我怎样才能格式化IPython html显示的pandas数据帧呢

  1. 数字是正确的
  2. 数字有逗号作为千位分隔符
  3. 大浮点数没有小数位

据我所知,numpy有设施set_printoptions,我可以这样做:

int_frmt:lambda x : '{:,}'.format(x)
np.set_printoptions(formatter={'int_kind':int_frmt})
Run Code Online (Sandbox Code Playgroud)

和其他数据类型类似.

但是,当在html中显示数据帧时,IPython不会选择这些格式选项.我还需要

pd.set_option('display.notebook_repr_html', True)
Run Code Online (Sandbox Code Playgroud)

但是如上所述的1,2,3.

编辑:下面是我对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))
Run Code Online (Sandbox Code Playgroud)

Vik*_*kez 25

HTML接收自定义的html数据字符串.没有人禁止您使用类的自定义CSS样式.dataframe(to_html方法添加到表中)传递样式标记.

所以最简单的解决方案是添加一个样式并将其与以下输出连接df.to_html:

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

但我建议为DataFrame定义一个自定义类,因为这将改变笔记本中所有表的样式(样式为"全局").

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

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

# 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'))
Run Code Online (Sandbox Code Playgroud)


Jul*_*rec 11

很久以前就问过这个问题.那时候,熊猫还没有包括pd.Styler.它已在版本中添加0.17.1.

以下是如何使用它来实现您期望的目标以及更多目标:

  • 中心标题
  • 右对齐任意数字列
  • 左对齐其他列.
  • 为您想要的数字列添加格式化程序
  • 使它成为每列具有相同的宽度.

这是一些示例数据:

In [1]:
df = pd.DataFrame(np.random.rand(10,3)*2000, columns=['A','B','C'])
df['D'] = np.random.randint(0,10000,size=10)
df['TextCol'] = np.random.choice(['a','b','c'], 10)
df.dtypes

Out[1]:
A          float64
B          float64
C          float64
D            int64
TextCol     object
dtype: object
Run Code Online (Sandbox Code Playgroud)

让我们使用df.style以下格式:

# Construct a mask of which columns are numeric
numeric_col_mask = df.dtypes.apply(lambda d: issubclass(np.dtype(d).type, np.number))

# Dict used to center the table headers
d = dict(selector="th",
    props=[('text-align', 'center')])

# Style
df.style.set_properties(subset=df.columns[numeric_col_mask], # right-align the numeric columns and set their width
                        **{'width':'10em', 'text-align':'right'})\
        .set_properties(subset=df.columns[~numeric_col_mask], # left-align the non-numeric columns and set their width
                        **{'width':'10em', 'text-align':'left'})\
        .format(lambda x: '{:,.0f}'.format(x) if x > 1e3 else '{:,.2f}'.format(x), # format the numeric values
                subset=pd.IndexSlice[:,df.columns[numeric_col_mask]])\
        .set_table_styles([d]) # center the header
Run Code Online (Sandbox Code Playgroud)

使用pd.Styler的结果


请注意.format,您可以很好地设置全局默认值,而不是调用子集列pd.options.display.float_format:

pd.options.display.float_format = lambda x: '{:,.0f}'.format(x) if x > 1e3 else '{:,.2f}'.format(x)
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是`df.style.set_prop .... render()`返回所需的html,而`df.to_html`则没有. (4认同)