使用Pandas向Excel工作表添加条件背景色

h43kikqp  于 2022-12-09  发布在  其他
关注(0)|答案(1)|浏览(328)

我一直在尝试将背景颜色应用到我的Pandas数据框,并使用styl.apply()将其保存到Excel文件中,但我没有看到背景颜色应用到Excel文件中。我尝试了许多方法,但结果都是一样的。
我的数据:
| 识别码|开始时间|结束时间|时差(_D)|
| - -|- -|- -|- -|
| 一个|2022年12月4日12时14分59秒|2022年12月4日12时29分05秒|十四|
| 2个|2022年12月4日12时44分32秒|2022年12月4日12:57:54|十三|
在这里,我尝试根据Time_Difference列中的值将背景色应用于Excel文件中的整行
下面是我的代码:

df_data = pd.read_sql(DATA_FETCH_QUERY, con=self.database_util.db_conn)
df_data.style.apply(lambda x: [
            'background:red' if x > 15 else ('background:yellow' if 10 < x <= 15 else 'background:white') for
            x in df_data.TIME_DIFFERENCE], axis=0)
df_data.to_excel(FILE_PATH, index=False)

我遗漏的代码有什么问题吗?
请帮我一下。先谢谢了。

3xiyfsfu

3xiyfsfu1#

将函数与numpy.selectStyler.apply配合使用,并将新DataFrame用于每行着色:

def coloring(x):
    c1 = 'background-color:red'
    c2 = 'background-color:white'
    c3 = 'background-color:yellow'

    arr = np.select([x['TIME_DIFFERENCE'] > 15, 
                     x['TIME_DIFFERENCE'] < 10],
                     [c1, c2], default=c3)
    return pd.DataFrame(np.broadcast_to(arr[:, None], x.shape),
                        index=x.index,
                        columns=x.columns)

styler = df_data.style.apply(coloring, axis=None).hide()

styler.to_excel(FILE_PATH, engine='openpyxl')

相关问题