计算特定行值出现的频率并用Python输出组合

2024-10-03 13:17:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV,其中包含销售数据,我想通过迭代来列出同一买家经常购买的类别。我想我可以用字典和a script like this来做到这一点,但我很难概念化如何计算同一个买家在不同类别中出现的次数。你知道吗

CSV数据示例:

buyer_id | order_id | category
1, 10, shoes
1, 11, outerwear
2, 12, beauty
2, 13, shoes
2, 14, outerwear

在这个例子中,我想知道鞋子,外套是一个组合至少2倍。你知道吗


Tags: csv数据id示例字典scriptbuyerthis
1条回答
网友
1楼 · 发布于 2024-10-03 13:17:57
import pandas as pd
#Creating dataframe
data = pd.DataFrame(
    {'Buyer_ID': [1,1,2,2,2,1],
     'Order_ID': [10,11,12,13,14,15],
     'Category':['shoes','outerwear','beauty','shoes','outerwear','shoes']
    })

data
Out[]: 
   Buyer_ID   Category  Order_ID
0         1      shoes        10
1         1  outerwear        11
2         2     beauty        12
3         2      shoes        13
4         2  outerwear        14
5         1      shoes        15

# Output: Same buyer and unique categories
data.groupby(["Buyer_ID", "Category"]).size()

# Buyer_ID:1 with two shoes entry is displayed only once (hence only unique categories are considered). 
Out[]: 
Buyer_ID  Category 
1         outerwear    1
          shoes        2
2         beauty       1
          outerwear    1
          shoes        1
dtype: int64 

相关问题 更多 >