Angel
Angel

Reputation: 47

Add a column from an existing dataframe into another between every other column

I'll try my best to explain this as I had trouble phrasing the title. I have two dataframes. What I would like to do is add a column from df1 into df2 between every other column. For example, df1 looks like this :

     Age    City       

0    34     Sydney     

1    30     Toronto    

2    31     Mumbai     

3    32     Richmond  

And after adding in df2 it looks like this:

    Name  Age  Clicks    City       Country

0   Ali   34     10     Sydney     Australia

1   Lori  30     20     Toronto    Canada

2  Asher  31     45     Mumbai     United States

3  Lylah  32     33     Richmond   United States

In terms of code, I wasn't quite sure where to even start.


'''Concatenating the dataframes'''
for i in range len(df2):
    pos = i+1
    df3 = df2.insert

#df2 = pd.concat([df1, df2], axis=1).sort_index(axis=1)
#df2.columns = np.arange(len(df2.columns))
#print (df2)

I was originally going to run it through a loop, but I wasn't quite sure how to do it. Any help would be appreciated!

Upvotes: 1

Views: 37

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195573

You can use itertools.zip_longest. For example:

from itertools import zip_longest

new_columns = [
    v
    for v in (c for a in zip_longest(df2.columns, df1.columns) for c in a)
    if not v is None
]

df_out = pd.concat([df1, df2], axis=1)[new_columns]
print(df_out)

Prints:

    Name  Age  Clicks      City        Country
0    Ali   34      10    Sydney      Australia
1   Lori   30      20   Toronto         Canada
2  Asher   31      45    Mumbai  United States
3  Lylah   32      33  Richmond  United States

Upvotes: 2

Related Questions