2

I have two dataframes:

print(df1) A B C 0 1 5 9 1 2 6 8 2 3 7 7 3 4 8 6 print(df2) D E F 0 1 5 9 1 2 6 8 2 3 7 7 3 4 8 6 

I want to insert columns D and E from df2 into df1 after column B.

The end result should be like this:

 A B D E C 0 1 5 1 5 9 1 2 6 2 6 8 2 3 7 3 7 7 3 4 8 4 8 6 

I know there's already a solution with the insert method with pandas:

df1.insert(1, "D", df2["D"]) df1.insert(2, "E", df2["E"])

However I would like to insert D and E at the same time. Like "transplant" it into df1, rather than having multiple inserts. (in real life the data to be transplanted is bigger which is why I want to avoid all the inserts)

My dataframes in dict format, so you can use DataFrame.from_dict():

 # df1 {'A': {0: 1, 1: 2, 2: 3, 3: 4}, 'B': {0: 5, 1: 6, 2: 7, 3: 8}, 'C': {0: 9, 1: 8, 2: 7, 3: 6}} # df2 {'D': {0: 1, 1: 2, 2: 3, 3: 4}, 'E': {0: 5, 1: 6, 2: 7, 3: 8}, 'F': {0: 9, 1: 8, 2: 7, 3: 6}} 
0

3 Answers 3

2

You can slice the dataframe df1 into two parts based on the location of column B, then concat these slices with columns D, E along the columns axis

i = df1.columns.get_loc('B') + 1 pd.concat([df1.iloc[:, :i], df2[['D', 'E']], df1.iloc[:, i:]], axis=1) 

 A B D E C 0 1 5 1 5 9 1 2 6 2 6 8 2 3 7 3 7 7 3 4 8 4 8 6 
Sign up to request clarification or add additional context in comments.

Comments

0

I think your solution is optimal. Alternatively you can:

df1[["D", "E"]] = df2[["D", "E"]] 

and then change the column order

Comments

0
import pandas as pd df1 = pd.DataFrame.from_dict({'A': {0: 1, 1: 2, 2: 3, 3: 4}, 'B': {0: 5, 1: 6, 2: 7, 3: 8}, 'C': {0: 9, 1: 8, 2: 7, 3: 6}}) df2 = pd.DataFrame.from_dict({'D': {0: 1, 1: 2, 2: 3, 3: 4}, 'E': {0: 5, 1: 6, 2: 7, 3: 8}, 'F': {0: 9, 1: 8, 2: 7, 3: 6}}) df1.merge(df2[['D', 'E']],on=df1.index) 

You can reorder based on your requirement

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.