假设我们有以下数据集:
orders = [
{'customer_id': 1, 'order_id': 1, 'quantity': 5, 'price': 10},
{'customer_id': 1, 'order_id': 2, 'quantity': 3, 'price': 15},
{'customer_id': 2, 'order_id': 3, 'quantity': 4, 'price': 20},
{'customer_id': 2, 'order_id': 4, 'quantity': 2, 'price': 8},
{'customer_id': 3, 'order_id': 5, 'quantity': 6, 'price': 12},
]
我们可以使用Python的collections
模块中的defaultdict
来按订单数量分组顾客数量和收入。下面是一个示例代码:
from collections import defaultdict
# 创建一个字典,用于存储每个订单数量对应的顾客数量和收入
customer_stats = defaultdict(lambda: {'count': 0, 'revenue': 0})
# 遍历每个订单
for order in orders:
quantity = order['quantity']
price = order['price']
customer_stats[quantity]['count'] += 1
customer_stats[quantity]['revenue'] += quantity * price
# 打印结果
for quantity, stats in customer_stats.items():
count = stats['count']
revenue = stats['revenue']
print(f"订单数量为{quantity}的顾客数量为{count},收入为{revenue}")
输出结果如下:
订单数量为5的顾客数量为1,收入为50
订单数量为3的顾客数量为1,收入为45
订单数量为4的顾客数量为1,收入为80
订单数量为2的顾客数量为1,收入为16
订单数量为6的顾客数量为1,收入为72
这样,我们就得到了按订单数量分组的顾客数量和收入。