如何在Apache Pig中按product_id统计商品总订购数量
按product_id统计商品总订购数量的实现方法
下面提供几种常用的实现方式,适配不同场景:
1. SQL 实现
如果数据存储在数据库中,直接用GROUP BY结合SUM()聚合函数就能完成统计,假设你的数据表名为orders,字段为product_id和quantity:
SELECT product_id, SUM(quantity) AS total_quantity FROM orders GROUP BY product_id;
执行后会直接返回按product_id分组的总订购量,格式和你预期的一致:
(11, 8) (12, 10) (13, 23)
2. Python 手动实现
如果数据是内存中的元组列表,用字典就能手动完成累加统计:
# 原始数据 order_data = [(11, 5), (11, 2), (11, 1), (12, 9), (12, 1), (13, 5), (13, 9), (13, 9)] # 初始化统计字典 total_dict = {} for product_id, qty in order_data: if product_id in total_dict: total_dict[product_id] += qty else: total_dict[product_id] = qty # 转换为预期的格式输出 for pid, total in total_dict.items(): print(f"({pid}, {total})")
运行后会输出你要的结果。
3. Python Pandas 实现
如果数据量较大,用Pandas库处理更高效:
import pandas as pd order_data = [(11, 5), (11, 2), (11, 1), (12, 9), (12, 1), (13, 5), (13, 9), (13, 9)] df = pd.DataFrame(order_data, columns=["product_id", "quantity"]) # 分组求和 result = df.groupby("product_id")["quantity"].sum().reset_index() # 按预期格式输出 for _, row in result.iterrows(): print(f"({row['product_id']}, {row['quantity']})")
内容的提问来源于stack exchange,提问作者byr
相关产品推荐
相关产品推荐

