pythondumb
pythondumb

Reputation: 1207

Pandas: Merging Multiple dataframes that are from two different lists

I have two lists where multiple dataframes are present

df_lst_1 = [df_1,df_2,df_3]
df_lst_2 = [df_4,df_5,df_6]

Now I am trying to merge the dataframes but with a rider. That said, I want df_1 to be merged with df_4, df_2 to df_5. I.e. element wise merging. If I use the following code, the same is not being achieved.

df_m = [] 
for p in df_lst_1:
  for c in df_lst_2:
    df_merge = p.merge(c,how='inner',on='KUNNR')
    df_m.append(df_merge)

The above codes produces 9 dataframes. However, I need three 'merged' dataframes.

Any clue on this? How to use 'zip' or 'map' function here?

Upvotes: 2

Views: 37

Answers (1)

jezrael
jezrael

Reputation: 862661

I believe you want zip and then merge in list comprehension:

df_m = [p.merge(c,how='inner',on='KUNNR') for p,c in zip(df_lst_1, df_lst_2)] 

Or use loop solution:

df_m = [] 
for p,c in zip(df_lst_1, df_lst_2):
    df_merge = p.merge(c,how='inner',on='KUNNR')
    df_m.append(df_merge)

Upvotes: 2

Related Questions