You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas DataFrame双条件行高亮求助:超4天In-Transit标红,Delivered标绿

DataFrame行按条件着色实现方案

实现思路

用pandas的Styler对象自定义行样式,通过判断每行的Transit Time和Status值,返回对应的背景色样式。

完整代码

import pandas as pd

# 创建示例DataFrame
Example = pd.DataFrame({
    'Tracking': ['1006879694', '2993851011', '7589912853','9833130823','2977450965','5811747185','9350589150','9350589161'],
    'Transit Time':[12,4,2,1,6,4,1,10],
    'Status':['In-Transit','In-Transit','In-Transit','In-Transit','Delivered','Delivered','Delivered','Delivered']
})

# 定义行着色规则函数
def color_rows(row):
    # 规则1:运输中且运输时长超4天,标浅红
    if row['Status'] == 'In-Transit' and row['Transit Time'] > 4:
        return ['background-color: #ffcccc'] * len(row)
    # 规则2:已签收,标浅绿
    elif row['Status'] == 'Delivered':
        return ['background-color: #ccffcc'] * len(row)
    # 其余情况保持白色背景
    else:
        return ['background-color: white'] * len(row)

# 应用样式并显示结果
styled_df = Example.style.apply(color_rows, axis=1)
styled_df

补充说明

  • axis=1参数指定按行遍历处理,函数返回的样式列表需与每行的列数匹配
  • 可自行替换十六进制颜色代码调整深浅(比如#ff0000是纯红,#00ff00是纯绿)
  • 若要导出带样式的表格到Excel,需安装openpyxl依赖,执行命令:pip install openpyxl,再调用:
styled_df.to_excel('styled_shipments.xlsx', engine='openpyxl', index=False)

内容的提问来源于stack exchange,提问作者Luciana Teles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 16:32:19