当值高于 python 的阈值时,突出显示 google 电子表格中列中的单元格

Highlight cells in a column in google spreadsheet when the value above a threshold with python

这是我的代码的简化示例和我想在 google 电子表格中获得的结果的屏幕截图。我希望将数据框样式保存到 google 电子表格,就像使用 python 将 table 样式应用到 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)

使用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 (Conditional Formatting)

gspread-dataframe