对 excel 中的样式数据应用 Lambda 函数

Applying the Lambda function for Style data in the excel

我在应用带有 lambda 函数的 applymap() 来替换 Styler Dataframe 中的现有字符串时遇到问题。 例如。我们必须用 'yellow' 颜色替换更改,用 'green' 替换新建。我坚持应用函数来替换 Styler Dataframe 中的值。

import pandas as pd

out=r'C:\Users\test\changes.xlsx'
df = pd.read_excel(r'C:\Users\test\update.xlsx')

def mycolors(val):
    #print(val)
    stra = 'Changed-'
    stri = 'New-'
    color = 'white'
    if stra in str(val):
        color = 'yellow'
    elif stri in str(val):
        color = 'green'
        #print(type(color))
    return 'background-color: %s' % color


df = df.style.applymap(mycolors)
df = df.applymap(lambda x: str(x).replace('Changed-',''))

#print(df)
df.to_excel(out, header=True, index=False)

在第一次应用映射之后,数据框现在是 pandas.styler。你想要做的是使用样式器的格式来访问单元格的文本:pandas.styler Styler.format: Formats the text display value of cells.

df = df.style.applymap(mycolors)
df = df.format(lambda x: str(x).replace('Changed-',''))

这个问题已通过使用 openpyxl 解决,方法是重新打开 excel 并替换其中的内容。