【问题标题】:Highlight cells in a column in google spreadsheet when the value above a threshold with python当使用python的值高于阈值时,突出显示谷歌电子表格中的列中的单元格
【发布时间】:2020-12-21 15:54:48
【问题描述】:

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

【问题讨论】:

标签: python pandas google-sheets google-sheets-api gspread


【解决方案1】:

使用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

【讨论】:

  • 这很有帮助!谢谢。我对此“GridRange.from_a1_range('B2:B', sh)]'有疑问。有没有办法使用列名而不是字母“B”?因为我需要将此条件格式应用于许多列,所以很难分辨每列的字母(“B”或“AZ”或“CZ”)。如果没有,是否可以检测出每个列名对应的字母是什么?谢谢
  • 不幸的是,ConditionalFormatRule 只接受 GridRange 作为 ranges 的值
猜你喜欢
  • 1970-01-01
  • 2014-03-20
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多