【问题标题】:Insert multiple rows to index [duplicate]插入多行以索引[重复]
【发布时间】:2019-01-11 19:39:09
【问题描述】:

我正在寻找一种在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]])

【问题讨论】:

    标签: python pandas insert


    【解决方案1】:

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

    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
    

    【讨论】:

    • 这适用于我拥有的多个切片。不是最佳的,但我会接受它。
    【解决方案2】:

    i 为插入位置。 i指的是准确的位置,不是基于索引的

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

    df 是您想要的数据框

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 2018-09-08
      • 2013-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多