![](/img/trans.png)
[英]Create two new data frames from two existing data frames, taking into account all combinations of their multi-index columns and their values
[英]Python: combine two data frames with all combinations of index
我有一个带有 x 变量和 id_number 1:n 的数据框(n 很大)。 我想创建一个新的数据框,根据数据框中的 id_number 水平合并每一对。 原始数据如下所示:
id_number var_x1 var_x2
1 sth stuff
2 other things
3 more info
我想为每一对可能的对得到这个:
id_numberA var_x1A var_x2A id_numberB var_x1B var_x2B
1 sth stuff 1 sth stuff
1 sth stuff 2 other things
1 sth stuff 3 more info
2 other things 3 more info
对于大型数据集,最有效的方法是什么?
您可以使用以下命令创建合并索引:
df['temp'] = 1
然后将dataframe
与自身合并:
merged_df = df.merge(df, on='temp', suffixes=('A', 'B')).drop('temp', axis=1)
如果您不想要相同id_number
的组合,请最后执行:
merged_df = merged_df[merged_df['id_numberA'] != merged_df['id_numberB']]
如果您不想重复混合id_numberA
和id_numberB
,请改为 finally:
merged_df = merged_df[merged_df['id_numberA'] < merged_df['id_numberB']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.