interactions_df = interactions[interactions['interaction_type'].isin([1,2,3])]
我有interaction_df数据帧。打印时显示为:
user_id item_id interaction_type created_at
1974005 2668706 1 1444154047
2690450 405777 1 1445338496
2690450 1180447 1 1444806365
2690450 1803133 1 1440480562
2081252 405777 1 1442346826
2081252 805572 1 1441286115
732722 1266442 1 1446745768
687093 2651366 1 1445373507
现在通过简单地将这些数据分组到'item_id'和'user_id',例如:
grouped = interactions_df.groupby(['item_id', 'user_id']).count()
print(grouped)
我得到了这个结果:
item_id user_id interaction_type created_at
405777 2690450 1 1
2081252 1 1
805572 2081252 1 1
1180447 2690450 1 1
1266442 732722 1 1
1803133 2690450 1 1
2651366 687093 1 1
2668706 1974005 1 1
现在我需要的是将我的数据存储在csv文件中,但是采用这种格式
item_id user_id
405777 2690450, 2081252
805572 2081252
1180447 2690450
1266442 732722
1803133 2690450
2651366 687093
2668706 1974005
如果单个项目有多个用户,那么我需要在逗号分隔的列表中只需要这两个列,没有其他信息或计数。
我怎样才能做到这一点?请建议。
感谢。
答案 0 :(得分:1)
我认为您可以先reset_index
删除Multiindex。然后再次groupby
和apply
join
(如果列user_id
是数字,则需要astype
将int
投射到string
最后写to_csv
:
grouped = interactions_df.groupby(['item_id', 'user_id'], as_index=False).count()
print(grouped)
item_id user_id interaction_type created_at
0 405777 2081252 1 1
1 405777 2690450 1 1
2 805572 2081252 1 1
3 1180447 2690450 1 1
4 1266442 732722 1 1
5 1803133 2690450 1 1
6 2651366 687093 1 1
7 2668706 1974005 1 1
df = grouped.groupby('item_id')['user_id'].apply(lambda x: ", ".join(x.astype(str)))
.reset_index()
print df
item_id user_id
0 405777 2081252, 2690450
1 805572 2081252
2 1180447 2690450
3 1266442 732722
4 1803133 2690450
5 2651366 687093
6 2668706 1974005
df.to_csv('file', index=False)
使用get_level_values
的另一个小疯狂解决方案:
grouped = interactions_df.groupby(['item_id', 'user_id']).count()
print grouped.index.get_level_values('user_id').to_series()
.groupby(grouped.index.get_level_values('item_id'))
.apply(lambda x: ", ".join(x.astype(str)))
.reset_index(name='user_id')
item_id user_id
0 405777 2081252, 2690450
1 805572 2081252
2 1180447 2690450
3 1266442 732722
4 1803133 2690450
5 2651366 687093
6 2668706 1974005