设置 pandas 索引单元格的背景颜色样式

Styling the background color of pandas index cell

我想更改 pandas table 的背景样式颜色。 示例:

df = pd.DataFrame({
'group': ['A','B','C','D'],
'var1': [38, 1.5, 30, 4],
'var2': [29, 10, 9, 34],
'var3': [8, 39, 23, 24],
'var4': [7, 31, 33, 14],
'var5': [28, 15, 32, 14]
})

df.set_index('group', inplace=True)

我想要索引单元格(并且只是索引单元格)A、C 的背景颜色为蓝色,B、D 为红色。

我查看了样式文档,但找不到符合这种情况的示例。

基于df.style的限制,未实现着色索引和列。

如果您可以根据索引为值着色,您可以这样做。创建字典并使用 index.map

根据索引应用颜色
c1 = 'background-color: blue'
c2 = 'background-color: red'
d = {"A":c1,"B":c2,"C":c1,"D":c2}

df.style.apply(lambda x: x.index.map(d))

我们可以通过查看 <th> 标签来操纵底层 HTML。一种方便的方法是使用 BeautifulSoup 库:

from bs4 import BeautifulSoup

# get the HTML representation
html = df.to_html()

# form the soup
soup = BeautifulSoup(html)

# the color categories
blues = {"A", "C"}
reds = {"B", "D"}

# for each possible "table header" tag...
for tag in soup.find_all("th"):
    # if tag's content is in `blues`...
    if tag.text in blues:
        # change the HTML style attribute accordingly
        tag["style"] = "background-color: blue;"
    # similar here..
    elif tag.text in reds:
        tag["style"] = "background-color: red;"

# get back the new HTML
new_html = str(soup)

然后,例如在 IPython 笔记本中:

from IPython.display import HTML

HTML(new_html)

给予

此功能当前不可用,下一个版本可能是 2021 年 12 月 (https://github.com/pandas-dev/pandas/pull/41893)。但是,您可以使用 table 样式轻松解决此问题。请参阅下面我的回答:

df = pd.DataFrame([[1,2],[3,4],[5,6],[7,8]], index=["A", "B", "C", "D"])
green = [{'selector': 'th', 'props': 'background-color: green'}]
red = [{'selector': 'th', 'props': 'background-color: red'}]
df.style.set_table_styles({"A": green, "B": red, "C": green, "D": red}, axis=1)