Reputation: 21
Is there a possibility to add a row from one dataframe into another at a specified position? I tried to modify this solution, but it is not working properly.
If I try the following operation, my row always gets added as a column:
df1 = pd.concat([df1[:2], df2[1], df1.iloc[2:]]).reset_index(drop=True)
print (df1)
A B C D 0
0 X X Y Y NaN
1 15 12 8 4 NaN
2 NaN NaN NaN NaN 15
3 NaN NaN NaN NaN 12
4 NaN NaN NaN NaN 8
5 NaN NaN NaN NaN 4
6 21 13 5 9 NaN
Separately they look like this
A B C D
0 X X Y Y
1 15 12 8 4
2 21 13 5 9
F G H J
0 A H C D
1 15 12 8 4
2 21 13 5 9
As said, I also tried it with rows from the same DataFrame
Upvotes: 1
Views: 3108
Reputation: 153470
IIUC:
df1 = pd.DataFrame({'Col1':['A']*5, 'Col2':['B']*5})
Col1 Col2
0 A B
1 A B
2 A B
3 A B
4 A B
df2 = pd.DataFrame(data=[['X','Z'],['W','U'],['T','S']],columns=['Col1','Col2'])
Col1 Col2
0 X Z
1 W U
2 T S
Insert row into df2 index row 1 into df1 between index row 2 and row 3:
pd.concat([df1[:2],df2.loc[1,:].to_frame().T,df1[2:]],ignore_index=True)
Output:
Col1 Col2
0 A B
1 A B
2 W U
3 A B
4 A B
5 A B
Upvotes: 2