简体   繁体   中英

How to merge pandas dataframes from two separate lists of dataframes

I have two lists of dfs

List1 = [df1,df2,df3]
List2 = [df4,df5,df6]

I want to merge the first df from List1 with the corresponding df from List 2. ie df1 with df4 and df2 with df5, etc.

The dfs share a common column, 'Col1'. I have tried the following code

NewList = []
for i in len(List1),len(List2):
    NewList[i]=pd.merge(List1[i],List2[i],on='Col1') 

I get the error 'list index out of range'.

I realise that this seems to be a common problem, however I cannot apply any of the solutions that I have found on Stack to my particular problem.

Thanks in advance for any help

Use

pd.concat(
    [df1, df2]
)

To loop over two lists and compare them or perform an operation on them element-to-element, you can use the zip() function.

import pandas as pd

List1 = [df1,df2,df3]
List2 = [df4,df5,df6]

NewList = []
for dfa, dfb in zip(List1, List2):
    # Merges df1, df4; df2, df5; df3, df6
    mdf = dfa.merge(dfb, on = 'Col1')
    NewList.append(mdf)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM