Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 使用条件合并多个数据帧列_Pandas_Dataframe_Merge - Fatal编程技术网

Pandas 使用条件合并多个数据帧列

Pandas 使用条件合并多个数据帧列,pandas,dataframe,merge,Pandas,Dataframe,Merge,我是熊猫的新手,我想合并两个数据帧,并对其应用多个条件。我有大师和贸易 master_df Country Product China Apple India Mango Germany Apple India Mango 主df[‘国家’]可以是出口,也可以是进口,我们可以从贸易df中获得 trade_df Export Import Product India US Mango China UK Apple India

我是熊猫的新手,我想合并两个数据帧,并对其应用多个条件。我有大师和贸易

master_df
Country Product
China    Apple
India    Mango
Germany  Apple
India    Mango
主df[‘国家’]可以是出口,也可以是进口,我们可以从贸易df中获得

trade_df
Export  Import   Product
India   US         Mango
China   UK         Apple
India   Germany    Apple 
我的最终目标是比较master_df[‘Country’]与贸易_df[‘Export’、‘Import’]以及这两种df的产品,得到如下输出:

master_df 
Country Product Export  Import 
China    Apple   China   UK
India    Mango   India   US
Germany  Apple   India  Germany
我不确定我是否正确,因为我有错误

master_df = master_df.merge(trade_df,  on =['country','Product'])

当您在
['Country','Product']
上说join时,您告诉pandas在两个数据帧上查找两列。但是,两个数据帧上的“country”列是不同的

在您的
master_df
中,它是
Country

但在您的
交易中,它是
导出
导入

此外,从您的期望中可以看出,您实际上希望在
Country=Export
Country=Import
上加入
master_-df
两次。因此,您需要将它们连接两次并将它们连接在一起

您应该做什么(请注意,两个列表中的列名顺序必须对应):

这将为您提供以下输出:

    Country Product Export  Import
0   China   Apple   China   UK
1   India   Mango   India   US
0   Germany Apple   India   Germany

你的剧本很有帮助。但是,如果同一个国家的进出口贸易都是相同的,我会得到重复的数据。@Lee234,你说你想“比较”这些国家,但我不明白你想在这些加入后如何进行比较。我建议您可以有两个单独的数据帧分别用于导入和导出。或者,您可以将更多样本数据(导致重复)和预期结果作为新问题发布,以查看是否有人可以提供帮助。感谢Cristopher并找到了删除重复的解决方案。示例trade df将是trade_df=pd.DataFrame({'Export':['India','China','India','China','China','Import':['US','UK','demand','China','China','Product:['Mango','Apple','Apple','Apple']})。中国的出口和进口都在那里。我删除了带有多个条件的行。
    Country Product Export  Import
0   China   Apple   China   UK
1   India   Mango   India   US
0   Germany Apple   India   Germany