嗨,我有一个庞大的数据集,如下所示
示例数据:-
customerId products
0 20
1 2|2|23|
0 111|29|11|11|33|11|33
3 164|227
1 2|2
现在我想按如下方式转换这个数据集
customerId products purchase_count
0 20 1
0 111 1
0 29 1
0 11 3
0 33 2
1 2 4
1 23 1
3 164 1
3 227 1
请帮帮我
最佳答案
这是 unnesting问题
df['products']=df.products.str.split('|')
s=unnesting(df,['products'])
s.groupby(s.columns.tolist()).size()
products customerId
11 0 3
111 0 1
164 3 1
2 1 4
20 0 1
227 3 1
23 1 1
29 0 1
33 0 2
dtype: int64
def unnesting(df, explode):
idx=df.index.repeat(df[explode[0]].str.len())
df1=pd.concat([pd.DataFrame({x:np.concatenate(df[x].values)} )for x in explode],axis=1)
df1.index=idx
return df1.join(df.drop(explode,1),how='left')
关于python - 如何使用 pandas 中的这个 "|"符号转换数据以用于推荐系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55015267/