小编lys*_*dad的帖子

如何使用熊猫获取包括每个组合在内的数量

我试图弄清楚哪些服装客户一起购买。我可以找出确切的组合,但是我不知道的问题是包含组合+其他的计数。

例如,我有:

Cust_num  Item    Rev
Cust1     Shirt1  $40
Cust1     Shirt2  $40
Cust1     Shorts1 $40
Cust2     Shirt1  $40
Cust2     Shorts1 $40
Run Code Online (Sandbox Code Playgroud)

这应导致:

Combo                  Count
Shirt1,Shirt2,Shorts1    1
Shirt1,Shorts1           2
Run Code Online (Sandbox Code Playgroud)

我能做的最好的就是独特的组合:

Combo                 Count
Shirt1,Shirt2,Shorts1   1
Shirt1,Shorts1          1
Run Code Online (Sandbox Code Playgroud)

我试过了:

df = df.pivot(index='Cust_num',columns='Item').sum()
df[df.notnull()] = "x"
df = df.loc[:,"Shirt1":].replace("x", pd.Series(df.columns, df.columns))
col = df.stack().groupby(level=0).apply(','.join)
df2 = pd.DataFrame(col)
df2.groupby([0]).size().reset_index(name='counts')
Run Code Online (Sandbox Code Playgroud)

但这仅仅是独特的计数。

python pandas

11
推荐指数
1
解决办法
655
查看次数

标签 统计

pandas ×1

python ×1