1

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

Lazyone
  • 21
  • 1
  • 4
  • Found a solution by trying... but would love to know why this is working and the other is not working: df1 = pd.concat([df1[:2], df2[1:2], df1.iloc[2:]]).reset_index(drop=True) – Lazyone Aug 29 '17 at 14:54
  • You should try the solution in my answer too. Basically, `df[...]` refers to a column while `df[..:..]` refers to a row subslice. – cs95 Aug 29 '17 at 14:57
  • Can you post df1 and df2 separately? – cs95 Aug 29 '17 at 15:11

1 Answers1

2

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
Scott Boston
  • 147,308
  • 15
  • 139
  • 187