简体   繁体   English

如何从两个单独的数据框列表合并熊猫数据框

[英]How to merge pandas dataframes from two separate lists of dataframes

I have two lists of dfs 我有两个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. 我想将List1中的第一个df与列表2中的相应df合并。即df1和df4以及df2和df5等。

The dfs share a common column, 'Col1'. dfs共享公共列'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. 我意识到这似乎是一个常见问题,但是我无法将在Stack上找到的任何解决方案应用于我的特定问题。

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. 要遍历两个列表并对其进行比较或对它们进行元素到元素的操作,可以使用zip()函数。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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