【发布时间】:2021-11-23 15:15:36
【问题描述】:
我有一个df:
product_id order_id category qty_sold sale_value
table_1 1 Tables 1 999
chair_1 1 Chairs 4 1000
table_1 2 Tables 1 999
chair_1 2 Chairs 2 500
table_2 3 Tables 1 999
chair_1 3 Chairs 4 1000
table_2 4 Tables 1 999
chair_2 4 Chairs 8 2500
table_1 5 Tables 1 999
chair_1 5 Chairs 2 500
是桌椅订单数据,每行有一个order_id和一个product_id。我试图回答哪些是最畅销的桌子和最畅销的椅子的最流行组合。
因此,基本上,我会将前 50 个 product_id 的表分配给每个表 product_id 我将分配与该表一起购买的前 n 个 product_ids 的椅子。 用那个购买意味着它共享相同的order_id。
我尝试创建的所需输出如下所示:
df_tables - qty_sold 最受欢迎的表格
product_id qty_sold chair_product_id chairs_sold times_sold
table_1 3 chair_1 6 2
chair_3 2 1
table_2 2 chair_1 4 1
chair_2 8 1
通过匹配order_id 并计算每个组合一起出现的次数,将购买的tables 和chairs 简单地组合在一起。
我试过了:
# Getting the list of most popular table product_ids
top_tables = df[df.category == 'Tables'] \
.groupby('product_id').sum().reset_index() \
.sort_values('qty_sold', ascending = False) \
.product_id.to_list()
most_popular_table = df[df.product_id == top_tables[0]].order_id.unique().tolist()
# getting top chairs bought with most popular table
df[(df.order_id.isin(most_popular_table)) & (df.category == 'Chairs')] \
.groupby('product_id').agg({'qty_ordered' : sum}) \
.sort_values('qty_ordered', ascending = False).reset_index()
哪个retuns(来自真实数据的样本)
product_id qty_ordered
4384 661
9974 247
8310 213
4032 166
9891 138
但是我想不出一种方法来创建我上面提到的每个前 50 名桌子的所需输出,然后是我检查顶级椅子和桌子的第二个输出。我想知道是否有一种巧妙的方法可以获得我想要的结构。
【问题讨论】:
标签: python pandas combinations