如何用Pandas、pygsheets为满足列对比条件的指定单元格上色
Pandas 样式单独标红price_2符合条件单元格
错误原因说明
- 原代码列表推导逻辑错误:遍历行内每个单元格值时,用行对象判断条件,导致所有单元格被设置为相同样式,最终整行染色
- 指定
subset='price_2'报错的原因:设置subset后,函数接收的入参仅为price_2单列的序列,不存在price_1字段,因此触发KeyError
正确实现代码
def highlight_late(row): # 初始化所有列的样式为空(不修改原有样式) styles = [''] * len(row) # 获取price_2列的索引位置 price2_idx = row.index.get_loc('price_2') # 仅当price_2小于price_1时,给price_2列设置红色背景 if row['price_2'] < row['price_1']: styles[price2_idx] = 'background-color: red' return styles # 应用样式 styled_df = myDataframe.style.apply(highlight_late, axis=1)
pygsheets 实现Google Sheet相同效果
推荐使用条件格式规则实现,无需遍历单元格,性能更高,适合任意数据量:
import pygsheets # 1. 认证并打开目标表格和工作表 gc = pygsheets.authorize(service_file='你的服务账号密钥文件路径.json') sh = gc.open('你的Google Sheet表格名称') wks = sh.worksheet_by_title('你的工作表名称') # 或直接用sh.sheet1取第一个工作表 # 2. 批量添加条件格式规则 # 假设sku在A列(索引0)、price_1在B列(索引1)、price_2在C列(索引2),第一行为表头 conditional_format_request = { "requests": [ { "addConditionalFormatRule": { "rule": { "ranges": [ { "sheetId": wks.id, "startColumnIndex": 2, # 仅作用于price_2所在的C列 "endColumnIndex": 3, "startRowIndex": 1 # 跳过第一行表头 } ], "booleanRule": { "condition": { "type": "CUSTOM_FORMULA", "values": [{"userEnteredValue": "=C2<B2"}] }, "format": { "backgroundColor": {"red": 1, "green": 0, "blue": 0} } } }, "index": 0 } } ] } sh.batch_update(conditional_format_request)
如果需要逐行判断处理,也可以用遍历单元格的方式:
# 获取所有表格值 all_rows = wks.get_all_values() # 从第二行开始遍历(跳过表头) for row_num in range(1, len(all_rows)): try: price1 = float(all_rows[row_num][1]) price2 = float(all_rows[row_num][2]) except (ValueError, IndexError): # 跳过非数字值或空行 continue if price2 < price1: # Google Sheet行号从1开始,C列对应列号3 target_cell = wks.cell((row_num + 1, 3)) target_cell.color = (1, 0, 0, 1) # RGBA格式,纯红色不透明
内容的提问来源于stack exchange,提问作者Yaroslav Butorin
相关产品推荐
相关产品推荐

