我想将 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/