If I have two dataframes:
df1:
df1 = pd.DataFrame({'A':[10,20,15,30,45], 'B':[17,33,23,10,12]})
A B
0 10 17
1 20 33
2 15 23
3 30 10
4 45 12
df2:
df2 = pd.DataFrame({'C':['cat'], 'D':['dog'], 'E':['emu'], 'F':['frog'], 'G':['goat'], 'H':['horse'], 'I':['iguana']})
C D E F G H I
0 cat dog emu frog goat horse iguana
How do I combine the two dataframes and fill df1
whereby each row is a replicate of df2
?
Here is what I have so far. The code works as intended, but if I were to have hundreds of columns, then I would anticipate there would be a much easier way than my current method:
Current Code:
df1 = df1.assign(C = lambda x: df2.C[0],
D = lambda x: df2.D[0],
E = lambda x: df2.E[0],
F = lambda x: df2.F[0],
G = lambda x: df2.G[0],
H = lambda x: df2.H[0],
I = lambda x: df2.I[0])
Expected output:
A B C D E F G H I
0 10 17 cat dog emu frog goat horse iguana
1 20 33 cat dog emu frog goat horse iguana
2 15 23 cat dog emu frog goat horse iguana
3 30 10 cat dog emu frog goat horse iguana
4 45 12 cat dog emu frog goat horse iguana
CodePudding user response:
Use:
df = df1.assign(**df2.iloc[0])
print (df)
A B C D E F G H I
0 10 17 cat dog emu frog goat horse iguana
1 20 33 cat dog emu frog goat horse iguana
2 15 23 cat dog emu frog goat horse iguana
3 30 10 cat dog emu frog goat horse iguana
4 45 12 cat dog emu frog goat horse iguana
CodePudding user response:
Use a cross merge?
df1.merge(df2, how='cross')
Output:
A B C D E F G H I
0 10 17 cat dog emu frog goat horse iguana
1 20 33 cat dog emu frog goat horse iguana
2 15 23 cat dog emu frog goat horse iguana
3 30 10 cat dog emu frog goat horse iguana
4 45 12 cat dog emu frog goat horse iguana