如何根据两列对熊猫数据框进行分组?

时间:2021-07-15 09:25:37

标签: python pandas dataframe jupyter-notebook analytics

我以这种方式有一个熊猫数据框对象:

enter image description here

我想从中创建多个数据帧,这些数据帧分组在 user 和 alt_user 列上。 基本上,每个新创建的数据帧都应该具有唯一的 user 和 alt_user 组合。

输出:

enter image description here

enter image description here

enter image description here

enter image description here

到目前为止我已经使用了 dataframe1.groupby(['user', 'alt_user']) 但这不会创建多个数据框。

1 个答案:

答案 0 :(得分:0)

dataframe1.groupby(['user', 'alt_user']) 并非旨在创建多个数据帧,事实上它甚至不会在没有聚合的情况下创建一个。 要执行您想要的操作,您需要从所有唯一对的列表开始,可以通过以下方式获得:

unique_pairs = set(zip(df.User, df.Alt_user))

那么数据框列表将是

dataframes = [dataframe1.loc[np.logical_and(dataframe1.User==user, dataframe1.Alt_user==alt_user), :] for user, alt_user in unique_pairs]