python - 使用 pandas 将 DataFrame 写入 html 时应用样式映射

标签 python pandas

我想将 pandas DataFrame 输出到 .html 并应用样式。文档* 给出了将负值显示为红色的示例。

import pandas as pd
import numpy as np

np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
df.iloc[0, 2] = np.nan

def color_negative_red(val):
    """
    Takes a scalar and returns a string with
    the css property `'color: red'` for negative
    strings, black otherwise.
    """
    color = 'red' if val < 0 else 'black'
    return 'color: %s' % color

s = df.style.applymap(color_negative_red)
s

我可以使用“to_html”方法输出格式化的 df 吗?从该文档**我看到有一个“格式化程序”选项,但我不知道如何在这种情况下应用它。

这是我如何编写未格式化的 df:

df.to_html(r'c:\temp\html.html')

* http://pandas.pydata.org/pandas-docs/stable/style.html

** http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_html.html

最佳答案

我不知道这是否是最好的(或惯用的)方法,但它应该有效:

with open('html.html', 'w') as html:
    html.write(s.render())

关于python - 使用 pandas 将 DataFrame 写入 html 时应用样式映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39922633/

相关文章:

python - 如何在 Python 中返回解压后的列表?

python - Pandas 中带有子范围的 GroupBy

python - Pandas DataFrame 中匹配行的索引 [Python]

Python Camelot - 如何从表中删除换行符/n

Python 装饰器类将方法转换为字典项

Python 正则表达式 - 字符串中的可选字段

python - 是否可以在未传递任何内容时将 help 作为默认参数吐出?

python - 使用 Pandas 添加来自不同表的属性

python - Pandas 多索引数据框将列中的第一行设置为 0

python - 为什么我在 matplotlib 中的绘图没有显示轴