我有两个数据框,一个是喜欢歌曲的客户,另一个数据框是用户及其群集。
DATA 1:
user song
A 11
A 22
B 99
B 11
C 11
D 44
C 66
E 66
D 33
E 55
F 11
F 77
DATA 2:
user cluster
A 1
B 2
C 3
D 1
E 2
F 3
使用上述数据集,我能够实现该群集用户收听所有歌曲的内容。
cluster songs
1 [11, 22, 33, 44]
2 [11, 99, 66, 55]
3 [11,66,88,77]
我需要将特定群集的歌曲分配给尚未收听的特定用户。 在我的预期输出A属于集群1,他还没有收听歌曲33和44 ..所以我的输出应该如下。对于B属于群集2,B没有收听66和55首歌曲,B的输出如下所示。
预期输出:
user song
A [33, 44]
B [66,55]
C [77]
D [11,22]
E [11,99]
F [66]
答案 0 :(得分:1)
不容易:
#add column and remove duplicates
df = pd.merge(df1, df2, on='user', how='left').drop_duplicates(['user','song'])
def f(x):
#for each group reshape
x = x.pivot('user','song','cluster')
#get all columns values if NaNs in data
x = x.apply(lambda x: x.index[x.isnull()].tolist(),1)
return x
df1 = df.groupby(['cluster']).apply(f).reset_index(level=0, drop=True).sort_index()
user
A [33, 44]
B [55, 66]
C [77]
D [11, 22]
E [11, 99]
F [66]
dtype: object
类似的解决方案:
df = pd.merge(df1, df2, on='user', how='left').drop_duplicates(['user','song'])
df1 = (df.groupby(['cluster']).apply(lambda x: x.pivot('user','song','cluster').isnull())
.fillna(False)
.reset_index(level=0, drop=True)
.sort_index())
#replace each True by value of column
s = np.where(df1, ['{}, '.format(x) for x in df1.columns.astype(str)], '')
#remove empty values
s1 = pd.Series([''.join(x).strip(', ') for x in s], index=df1.index)
print (s1)
user
A 33, 44
B 55, 66
C 77
D 11, 22
E 11, 99
F 66
dtype: object
答案 1 :(得分:1)
使用集进行比较。
<强>设置强>
df1
# user song
# 0 A 11
# 1 A 22
# 2 B 99
# 3 B 11
# 4 C 11
# 5 D 44
# 6 C 66
# 7 E 66
# 8 D 33
# 9 E 55
# 10 F 11
# 11 F 77
df2
# user cluster
# 0 A 1
# 1 B 2
# 2 C 3
# 3 D 1
# 4 E 2
# 5 F 3
df3
# cluster songs
# 0 1 [11, 22, 33, 44]
# 1 2 [11, 99, 66, 55]
# 2 3 [11, 66, 88, 77]
<强>计算强>
df = df1.groupby('user')['song'].apply(set)\
.reset_index().rename(columns={'song': 'heard'})
df['all'] = df['user'].map(df2.set_index('user')['cluster'])\
.map(df3.set_index('cluster')['songs'])\
.map(set)
df['not heard'] = df.apply(lambda row: row['all'] - row['heard'], axis=1)
<强>结果强>
user heard all not heard
0 A {11, 22} {33, 11, 44, 22} {33, 44}
1 B {11, 99} {99, 66, 11, 55} {66, 55}
2 C {66, 11} {88, 66, 11, 77} {88, 77}
3 D {33, 44} {33, 11, 44, 22} {11, 22}
4 E {66, 55} {99, 66, 11, 55} {11, 99}
5 F {11, 77} {88, 66, 11, 77} {88, 66}
提取您需要的任何列;转换为列表很简单,即df[col] = df[col].map(list)
。
<强>解释强>
有3个步骤: