【问题标题】:Insert new dataframe to existing dataframe into specific row position in Pandas将新数据框插入现有数据框到 Pandas 中的特定行位置
【发布时间】:2020-04-17 06:00:44
【问题描述】:
我有一个df1 和df2 如下:
df1:
a b c
0 1 2 4
1 6 12 24
2 7 14 28
3 4 8 16
4 3 6 12
df2:
a b c
0 7 8 9
1 10 11 12
如何在第二行之后插入 df2 到 df1?我想要的输出是这样的。
a b c
0 1 2 4
1 6 12 24
2 7 8 9
3 10 11 12
4 7 14 28
5 4 8 16
6 3 6 12
谢谢。
【问题讨论】:
标签:
python
pandas
dataframe
【解决方案1】:
这是使用np.r_的另一种方式:
df2.index=range(len(df1),len(df1)+len(df2)) #change index where df1 ends
final=pd.concat((df1,df2)) #concat
final.iloc[np.r_[0,1,df2.index,2:len(df1)]] #select ordering with iloc
#final.iloc[np.r_[0:2,df2.index,2:len(df1)]]
a b c
0 1 2 4
1 6 12 24
5 7 8 9
6 10 11 12
2 7 14 28
3 4 8 16
4 3 6 12
【解决方案2】:
使用concat,首先将DataFrame 与DataFrame.iloc分开:
df = pd.concat([df1.iloc[:2], df2, df1.iloc[2:]], ignore_index=False)
print (df)
a b c
0 1 2 4
1 6 12 24
0 7 8 9
1 10 11 12
2 7 14 28
3 4 8 16
4 3 6 12