首页 > 解决方案 > 当使用python的值高于阈值时,突出显示谷歌电子表格中的列中的单元格

问题描述

这是我的代码的简化示例以及我想在谷歌电子表格中获得的结果的屏幕截图。我希望将数据框样式保存到谷歌电子表格中,就像使用 python 将表格样式应用于 excel 一样。或者当值高于阈值时,使用 gspread-formatting 突出显示单元格背景。

谁能给我一个例子如何做到这一点?谢谢你!

cars = {'Brand': ['Honda Civic','Ferrari','Toyota Corolla','Ford Focus','Audi A4','TESLA','Ford Fusion','BENZ'],
        'Price': [22000,625000,25000,27000,35000,55000,28000,51000]}
df_car = pd.DataFrame(cars, columns = ['Brand', 'Price'])

def _color_if_above_budget(s):
    return ['background-color: red' if val >50000 else '' for val in s]
s=df_car.style.apply(_color_if_above_budget, subset=['Price'])
ws=**worksheet
        gd.set_with_dataframe(worksheet=ws,dataframe=df_car,include_index=False,include_column_header=True,resize=True)

在此处输入图像描述

标签: pythonpandasgoogle-sheetsgoogle-sheets-apigspread

解决方案


用于gspread_dataframe将数据设置为工作表,并gspread_formatting根据条件格式化工作表的内容。

试试下面的代码:

import gspread
import pandas as pd
from gspread_dataframe import set_with_dataframe
from gspread_formatting import *

gc = gspread.service_account()
sh = gc.open("example").sheet1
cars = {'Brand': ['Honda Civic','Ferrari','Toyota Corolla','Ford Focus','Audi A4','TESLA','Ford Fusion','BENZ'],
        'Price': [22000,625000,25000,27000,35000,55000,28000,51000]}
df_car = pd.DataFrame(cars, columns = ['Brand', 'Price'])
set_with_dataframe(sh, df_car)

rule = ConditionalFormatRule(
    ranges=[GridRange.from_a1_range('B2:B', sh)],
    booleanRule=BooleanRule(
        condition=BooleanCondition('NUMBER_GREATER', ['50000']),
        format=CellFormat(textFormat=textFormat(bold=True), backgroundColor=Color(1,0,0))
    )
)
rules = get_conditional_format_rules(sh)
rules.append(rule)
rules.save()

输出:

示例图像

参考:

gspread-formatting(条件格式)

gspread-dataframe


推荐阅读