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

如何用Pandas关联product_id与status并统计状态32的商品数量

Python实现订单商品状态统计

核心思路

只用Python标准库就能高效完成:遍历所有订单,筛选出status=32的订单,再遍历这些订单里的商品ID,逐个计数,最后输出统计结果。

代码实现

1. 加载JSON数据

假设你的订单数据存在orders.json文件里,先加载数据:

import json
from collections import defaultdict

# 加载JSON文件
with open('orders.json', 'r', encoding='utf-8') as f:
    orders = json.load(f)

如果数据是直接以字符串形式存在代码里,替换成:

orders = json.loads(你的JSON字符串变量)

2. 统计符合条件的商品ID

用defaultdict自动初始化计数(新手友好,不用手动处理键不存在的情况):

product_status_counts = defaultdict(int)

for order in orders:
    # 只处理status为32的订单
    if order.get('status') == 32:
        # 遍历订单里的所有商品
        for item in order.get('items', []):
            product_id = item.get('product_id')
            if product_id:  # 防止商品ID为空的情况
                product_status_counts[product_id] += 1

如果不想用defaultdict,用普通字典也可以:

product_status_counts = {}

for order in orders:
    if order.get('status') == 32:
        for item in order.get('items', []):
            product_id = item.get('product_id')
            if product_id:
                product_status_counts[product_id] = product_status_counts.get(product_id, 0) + 1

3. 生成统计表格

直接打印格式化的表格,方便查看:

# 打印表头
print(f"{'商品ID':<10} {'status=32的订单数量':<20}")
print("-" * 30)

# 遍历统计结果打印
for product_id, count in product_status_counts.items():
    print(f"{product_id:<10} {count:<20}")

补充说明

  • 代码时间复杂度为O(N+M),N是订单总数,M是所有订单的商品总数,比手动处理效率提升明显
  • 用get()方法访问字典键,能避免因字段缺失(比如订单无items、商品无product_id)导致的报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 01:35:25