python - 当使用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)
解决方案
用于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()
输出:
参考:
推荐阅读
- jquery - 从嵌套的点击函数返回函数值
- java - 如何在运行时更改日志级别而不重新启动 Vert.x 应用程序
- android - 广播接收机未刷新移动电池电源更换数据
- javascript - 在 c# mvc 中的 javaScript 中将 html 代码作为字符串传递
- android - 如何在一个类中活动到另一个传递字符串值的类?
- android - 为什么在将 gradle 项目添加到另一个 repo 后,即使构建工作,IDE 中也会出现语法错误?
- sql-server - 将分钟添加到当前日期并使用溢出分钟创建一个新行
- jxbrowser - JxBrowser onStartLoadingFrame 数据传递问题
- python - python中的None,True,False是什么?
- android - 添加 firebase 后,所有 com.android.support 库必须使用完全相同的版本规范