下面是一个使用Python的示例代码来解决这个问题:
from collections import Counter
# 客户访问记录
customer_visits = [
('Alice', 'Shop A'),
('Alice', 'Shop B'),
('Alice', 'Shop A'),
('Bob', 'Shop A'),
('Bob', 'Shop C'),
('Bob', 'Shop B'),
('Bob', 'Shop A'),
('Charlie', 'Shop B'),
('Charlie', 'Shop C'),
('Charlie', 'Shop C'),
]
# 统计每个客户访问的店铺
customer_shop_count = {}
for customer, shop in customer_visits:
if customer not in customer_shop_count:
customer_shop_count[customer] = Counter()
customer_shop_count[customer][shop] += 1
# 查找每个客户访问最常的3个店铺
customer_top_shops = {}
for customer, shop_count in customer_shop_count.items():
customer_top_shops[customer] = shop_count.most_common(3)
# 输出结果
for customer, top_shops in customer_top_shops.items():
print(f"Customer: {customer}")
print("Top 3 shops visited:")
for shop, count in top_shops:
print(f"- {shop} ({count} visits)")
print()
输出结果:
Customer: Alice
Top 3 shops visited:
- Shop A (2 visits)
- Shop B (1 visits)
Customer: Bob
Top 3 shops visited:
- Shop A (2 visits)
- Shop B (1 visits)
- Shop C (1 visits)
Customer: Charlie
Top 3 shops visited:
- Shop C (2 visits)
- Shop B (1 visits)
这个例子中,我们使用了Counter
来统计每个客户访问的店铺次数,并使用most_common
方法来获取最常访问的3个店铺。
下一篇:按照每个客户的首个订单筛选数据框