Python pandas:合并两个没有键的表(将 2 个数据帧相乘并广播所有元素;NxN 数据帧)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35234012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python pandas : Merge two tables without keys (Multiply 2 dataframes with broadcasting all elements; NxN dataframe)
提问by notilas
I want to merge 2 dataframes with broadcast relationship: No common index, just want to find all pairs of the rows in the 2 dataframes. So want to make N row dataframe x M row dataframe = N*M row dataframe. Is there any rule to make this happen without using itertool?
我想合并 2 个具有广播关系的数据帧:没有公共索引,只想找到 2 个数据帧中的所有行对。所以想让 N 行数据帧 x M 行数据帧 = N*M 行数据帧。是否有任何规则可以在不使用 itertool 的情况下实现这一点?
DF1=
id quantity
0 1 20
1 2 23
DF2=
name part
0 'A' 3
1 'B' 4
2 'C' 5
DF_merged=
id quantity name part
0 1 20 'A' 3
1 1 20 'B' 4
2 1 20 'C' 5
3 2 23 'A' 3
4 2 23 'B' 4
5 2 23 'C' 5
回答by jezrael
You can use helper columns tmpfilled 1in both DataFramesand mergeon this column. Last you can dropit:
您可以使用助手栏tmp填写1在这两个DataFrames和merge在此列。最后你可以drop:
DF1['tmp'] = 1
DF2['tmp'] = 1
print DF1
id quantity tmp
0 1 20 1
1 2 23 1
print DF2
name part tmp
0 'A' 3 1
1 'B' 4 1
2 'C' 5 1
DF = pd.merge(DF1, DF2, on=['tmp'])
print DF
id quantity tmp name part
0 1 20 1 'A' 3
1 1 20 1 'B' 4
2 1 20 1 'C' 5
3 2 23 1 'A' 3
4 2 23 1 'B' 4
5 2 23 1 'C' 5
print DF.drop('tmp', axis=1)
id quantity name part
0 1 20 'A' 3
1 1 20 'B' 4
2 1 20 'C' 5
3 2 23 'A' 3
4 2 23 'B' 4
5 2 23 'C' 5

