我在应用带有 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)