Python pandas: merging two tables without keys (multiplexing 2 data frames with translation of all elements, NxN dataframe)

I want to combine 2 data frames with a broadcast relation: There is no common index, I just want to find all pairs of rows in 2 data frames. So you want to make N lines of data frame x M dataframe = N * M data line. Is there a rule for this to happen without using 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
+4
source share
1 answer

You can use auxiliary columns tmpfilled 1in DataFramesand mergein this column. Finally you can 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
+4
source

Source: https://habr.com/ru/post/1627511/


All Articles