[英]Highlight cells in a column in google spreadsheet when the value above a threshold with python
这是我的代码的简化示例以及我想在谷歌电子表格中获得的结果的屏幕截图。 我希望将 dataframe 样式保存到谷歌电子表格,因为使用 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()
Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.