3

I'm looking for a concise way of inserting rows in the middle of a DataFrame so that the rows after the insertion point are pushed forward. It would look something like this:

Data Frame A      Data Frame B
Idx | C1 | C2     Idx | C1 | C2 
----+----+----    ----+----+----
 0  | 12 | 31      0  | 49 | 67 
 1  | 64 | 98      1  | 25 | 63 
 2  | 47 | 10

Inserting B to A[2]:
Idx | C1 | C2
----+----+----
 0  | 12 | 31
 1  | 64 | 98
 2  | 49 | 67     # B[0]
 3  | 25 | 63     # B[1]
 4  | 47 | 10

This would have to be done for multiple data frames, or rather slices of the original. There's always the option of looping through with pd.concat and the slice and insert indices, but for a library like pandas I'd expect someone to already have come up with an answer I haven't come across.

append doesn't quite work, but it's close. There actually exists df.insert, but it's for columns. I'd appreciate any pointers even to helpful documentation.

Sandbox:

a = pd.DataFrame([[1, 2], [2, 3], [3, 4]])
b = pd.DataFrame([[4, 5], [5, 6]])
Felix
  • 2,548
  • 19
  • 48

2 Answers2

3

I think the best way is just to slice and concatenate:

insertion_point = 2

pd.concat([a.iloc[:insertion_point], b, a.iloc[insertion_point:]]).reset_index(drop=True)

   0  1
0  1  2
1  2  3
2  4  5
3  5  6
4  3  4
sacuL
  • 49,704
  • 8
  • 81
  • 106
0

Let i be the position of insertion. i refers to the exact position, not based on the index

df = A.loc[:i]
df.append(B,ignore_index = True)
df.append(A.loc[i:],ignore_index=True)

df is your desired dataframe

Rushabh Mehta
  • 1,529
  • 1
  • 13
  • 29