0

我在应用带有 lambda 函数的 applymap() 来替换 Styler Dataframe 中的现有字符串时遇到问题。例如,我们必须将 Change 替换为“yellow”,将 New 替换为“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)

4

2 回答 2

0

在第一个 applymap 之后,数据框现在是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-',''))
于 2020-05-18T20:10:33.183 回答
0

通过使用 openpyxl,重新打开 excel 并替换其中的内容,这个问题得到了解决。

点击这里

于 2020-05-19T19:19:27.830 回答