如何将多个但特定的行从一个数据框添加到另一个数据框

How to add multiple but specific rows from one dataframe to another

我正在尝试将一个数据中的一组特定行添加到另一个数据中,但我似乎无法弄清楚。我确信有比一次添加一行更好的方法。

df1= pd.DataFrame([['a', 1, 'John'], ['b', 2, 'Marry'], ['c', 3, 'Debbie']], columns= ['letter', 'number', 'names'])
df2= pd.DataFrame([['w', 6, 'Jim'], ['x', 33, 'Paul'], ['r', 12, 'Logan']],['m', 10, 'Olive']],['j', 88, 'Maya']], columns= ['letter', 'number', 'names'])

我希望能够从 df2 中提取包含 Jim、Paul 和 Logan 信息的前 3 行并将其添加到 df1。

预先感谢您提供的所有帮助。

您可以按如下方式使用.append() together with .iloc[]

df1 = df1.append(df2.iloc[:3]).reset_index(drop=True)

结果:

  letter  number   names
0      a       1    John
1      b       2   Marry
2      c       3  Debbie
3      w       6     Jim
4      x      33    Paul
5      r      12   Logan

.reset_index(drop=True)用于重新序列化索引