为什么将样式化的 pandas 数据框导出到 Excel 不起作用?

Why does the export of a styled pandas dataframe to Excel not work?

我想对每个 PEOPLE 实例具有名称和相关名称的单元格应用相同的背景颜色。我试过 df.style.applymap,它没有 return 错误,但它似乎不起作用。任何人有任何想法为什么?谢谢。

   clrs = list(mcolors.CSS4_COLORS.keys())
   for k in range(len(PEOPLE)):
        if PEOPLE[k].attribute == 'child':
            df1_data = [PEOPLE[k].name, PEOPLE[k].related]
    
            df.style.applymap([lambda x: 'background-color: yellow' if x in df1_data else 'background-color: red'])
    

    df.to_excel('styledz.xlsx', engine='openpyxl')

Here 是关于 df.style 的更多信息。我在这里使用一些简单的例子,因为我没有你的可用数据:

import pandas as pd
import numpy as np

df = pd.DataFrame({'a': np.random.randint(0, 10, 10), 'b': np.random.randint(0, 10, 10), 'late': np.random.choice([0, 1], 10).astype(np.bool)})

def highlight_late(s):
    return ['background-color: red' if s['late'] else 'background-color: green' for s_ in s]
df = df.style.apply(highlight_late, axis=1)
df.to_excel('style.xlsx', engine='openpyxl')

在 excel 文件中看起来像这样:


对于基于 cell 的着色使用:

def highlight_late(s):
    return ['background-color: red' if s_ else 'background-color: green' for s_ in s]


df = df.style.apply(highlight_late, subset=["late"], axis=1)

这给你:

基本上您的解决方案将是对以下内容的修改:

df = DataFrame([['mark', 2], ['mike', 4], ['manny', 6]], columns=['name', 'attribute']) 
def style_row(row, people):
    output = Series("", index=row.index)
    if row["name"] in people:
        output['attribute'] = "background-color:red;"
    return output
styler = df.style.apply(style_row, axis=1, people=['mark', 'manny'])
styler