使用列表添加单元格背景色并保存到excel

2024-06-16 12:08:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有如下数据帧。 enter image description here

我想根据条件更改背景颜色,最后我想保存到excel。 有以下几种情况:

  • 条件1:精确匹配&;区分大小写=错误-->;红色的
  • 条件2:包含&;区分大小写=错误-->;黄色的
  • 条件3:再次重复相同的字符3-->;蓝色

  • 列出条件1=[us,ca]

  • 列出条件1=[苹果,山姆]
  • 条件3的列表=[xxx,xxxx,XXXXXXXXXX,bbb,aaa]

这是预期产出。 enter image description here

我发现下面的代码使用stype.applymap,但无法应用此案例

styled = (df.style.applymap(lambda v: 'background-color: %s' % 'green' if v=='col' else ''))
styled.to_excel('d:/temp/styled.xlsx', engine='openpyxl')

我怎样才能解决这个问题


Tags: 数据gt颜色错误情况条件字符excel
1条回答
网友
1楼 · 发布于 2024-06-16 12:08:01

我将定义一个单独的函数来反映您的条件和applymap

def colorize(x):
    try:
        lower = x.lower()
        # condition 1, pass the corresponding list
        if lower in ['us','ca']: return 'background-color: red'

        # condition 2
        for s in ['apple', 'sam']: 
            if s in lower: return 'background-color: yellow'

        # condition 3
        for s in ['xxx','bbb', 'aaa']:
            if s in lower: return 'background-color:  blue'

        return ''
   except:
        return ''

# toy data
df = pd.DataFrame({'Country':['USA','us','usa','ca', 'CA'],
                   'V1':["Apple", "Applex", 'APPLE', 'SAMSUNG','xxx'],
                   'V2':['Samsung', 'Semsung', 'SamSung1', 'apple', 'bbbb'],
                   'V3':['SAMSUNG', 'SS','APPLEXX', 'APPLEs', 'aaa']
                   })

df.style.applymap(colorize)

输出:

enter image description here

相关问题 更多 >