为 Pandas 中的单元格着色

Coloring Cells in Pandas

我可以使用 Pandas 从 excel 文件导入数据,方法是:

xl = read_excel('path_to_file.xls', 'Sheet1', index_col=None, na_values=['NA'])    

现在我将 xl 中的所有数据都作为 DataFrame。我想根据另一个函数中定义的条件为该数据中的某些单元格着色,并将其(使用颜色编码)导出到 Excel 文件。

谁能告诉我应该怎么做?

谢谢。

尝试这样的事情:

with pandas.io.excel.ExcelWriter(path=Path, engine="xlsxwriter") as writer:
   sheet = writer.book.worksheets()[0]
   sheet.write(x, y, value, format) #format is what determines the color etc.

更多信息在这里:https://xlsxwriter.readthedocs.org/format.html

关于 Pandas website 上的单元格样式有很多想法。 但是提到:这是一项新功能,仍在开发中。我们将添加功能并可能在未来的版本中进行重大更改

Pandas 有一个相对较新的 Styler 功能,您可以在其中对数据帧应用条件格式类型操作。 http://pandas.pydata.org/pandas-docs/stable/style.html

您可以使用它们的一些内置函数,如 background_gradientbar 来复制类似 excel 的功能,如条件格式和数据栏。您还可以格式化单元格以显示百分比、浮点数、整数等,而无需更改原始数据框。

这是您可以使用 Styler 制作的图表类型的示例(这是一个无意义的图表,但只是为了演示功能):

要利用 Styler 的全部功能,您应该使用 Styler.apply()Styler.applymap() API 获得舒适 table。这些允许您创建自定义函数并将它们应用于 table 的列、行或元素。例如,如果我想将 +ive 单元格涂成绿色,将 -ive 单元格涂成红色,我会创建一个函数

def _color_red_or_green(val):
    color = 'red' if val < 0 else 'green'
    return 'color: %s' % color

并在我的 Styler 对象上调用它,即 df.style.applymap(_color_red_or_green).

关于导出回 Excel,据我所知 Styler 不支持,所以如果您需要 [=40],我可能会选择 xlsxwriter 路线=] 出于某种原因。然而,根据我的经验,这是一个很好的纯 Python 替代方案,例如与 matplotlib 图表和 emails/reports.

如果您只想突出显示某些值,最简单的方法是使用 applymap 和 lambda:

df.style.applymap(lambda x: "background-color: red" if x>0 else "background-color: white")