首页 > 解决方案 > 插入多行索引

问题描述

我正在寻找一种在 a 中间插入行的简洁方法,DataFrame以便将插入点之后的行向前推。它看起来像这样:

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

这必须针对多个数据帧,或者更确切地说是原始数据的切片来完成。总是可以选择循环遍历pd.concat切片和插入索引,但是对于像pandas我这样的库,我希望有人已经想出了我没有遇到的答案。

append不太好用,但很接近。实际上存在df.insert,但它是用于列的。我会很感激任何关于有用文档的指针。

沙盒:

a = pd.DataFrame([[1, 2], [2, 3], [3, 4]])
b = pd.DataFrame([[4, 5], [5, 6]])

标签: pythonpandasinsert

解决方案


我认为最好的方法就是切片和连接:

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

推荐阅读