我有一张顾客购买产品类别的表格。我正在尝试建立一个交叉销售矩阵,计算每个产品类别的唯一客户,并且总计也有唯一的数量。
pandas.crosstab
是一个很好的开始方式,但在小计上失败(即margins=True
)
df = pd.DataFrame({
'cust': ['1', '1', '2', '3', '3', '4', '5'], # customer ID
'categ': ['a', 'b', 'a', 'a', 'b', 'b', 'b'] # category ID
})
# have 2 columns to make the crosstab
dd = pd.merge(df, df, on='cust')
然后pd.crosstab(dd.categ_x, dd.categ_y, margins=True)
给出:
| categ_x | a | b | All |
|---------|---|---|-----|
| a | 3 | 2 | 5 |
| b | 2 | 4 | 6 |
| All | 5 | 6 | 11 |
pd.merge
有助于用交叉稳定的正确数字填充细胞,但导致小计/边缘的计数错误
我期望的是:
| categ_x | a | b | All |
|---------|---|---|-----|
| a | 3 | 2 | 3 | -- I have 3 unique clients with 'a'
| b | 2 | 4 | 4 | -- I have 4 unique clients with 'b'
| All | 3 | 4 | 5 | -- I have 5 unique clients in total
到目前为止,我已经尝试了一些计数,独特......没有太大的成功。
编辑
jezrael答案很好,但我想知道他们是否可以直接通过crosstab
,使用正确的aggfunc
。
您可以通过groupby.nunique
计算值并通过join
和append
手动添加值:
s = df2.groupby(['categ'])['cust'].nunique().rename('All')
s1 = s.append(pd.Series({'All': df2['cust'].nunique()}, name='All'))
df = pd.crosstab(dd.categ_x, dd.categ_y).join(s).append(s1)
print (df)
a b All
categ_x
a 3 2 3
b 2 4 4
All 3 4 5
另一个类似的解
s = df2.groupby(['categ'])['cust'].nunique().rename('All')
df = pd.crosstab(dd.categ_x, dd.categ_y).join(s).append(s)
df.loc['All','All'] = df2['cust'].nunique()
df = df.astype(int)
print (df)
a b All
categ_x
a 3 2 3
b 2 4 4
All 3 4 5
我想这就是我需要的:
pd.crosstab(
dd.categ_x, dd.categ_y, margins=True,
values=dd.cust, aggfunc=pd.Series.nunique
)
得到:
| categ_x | a | b | All |
|---------|---|---|-----|
| a | 3 | 2 | 3 |
| b | 2 | 4 | 4 |
| All | 3 | 4 | 5 |
pd.Series.nunique
给出了values
(这里是dd.cust
)的独特值的长度/大小。