2 回答

TA贡献1877条经验 获得超1个赞
首先,获取唯一的用户 ID 并随机排列它们:
uniques = np.random.permutation(df['user_id'].unique())
拆分唯一 ID(假设每个拆分 2 个 ID):
splits = np.array_split(uniques, len(uniques) // 2)
定义一个基于索引值对行进行分组的函数:
def grouper(value):
return np.argmax([value in split for split in splits])
并使用它:
for group in df.set_index('user_id').groupby(grouper):
print(group)

TA贡献1900条经验 获得超5个赞
据我了解,您可以使用:
d={'df'+str(e):df[df.user_id.isin(i)] for e,i in
enumerate(np.array_split(np.random.permutation(df.user_id.unique()),
len(df.user_id.unique())/2))}
输出
{'df0': user_id movie_id rating
26184 2 1 4
18504 10 1 4
4617 10 4 4, 'df1': user_id movie_id rating
32236 1 1 5
23171 1 2 3
83307 1 3 4
62631 1 4 3
47638 1 5 3
52430 7 4 5, 'df2': user_id movie_id rating
1333 5 1 4
172 5 2 3
54487 6 1 4}
您可以调用此字典中的每个键:
print(d['df1'])
user_id movie_id rating
32236 1 1 5
23171 1 2 3
83307 1 3 4
62631 1 4 3
47638 1 5 3
52430 7 4 5
添加回答
举报