2

I have a df1 and df2 as follows:

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 

How can I insert df2 to df1 but after the second row? My desired output will like this.

 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 

Thank you.

2 Answers 2

2

Use concat with splitted first DataFrame by 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 
Sign up to request clarification or add additional context in comments.

Comments

1

Here is another way using 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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.