合并2个数据框 [英] Combining 2 dataframes

查看:198
本文介绍了合并2个数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想合并2个相似的数据框.我已经检查了几个网站,但找不到我的问题的答案.

I want to combine 2 similar dataframes. I I have checked several websites but couldn't find an answer to my question.

df1 = DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
                 'B': ['B0', 'B1', 'B2', 'B3'],
                 'C': ['C0', 'C1', 'C2', 'C3'],
               index=[0, 1, 2])   
df2 = DataFrame({'A': ['A0', 'A1', 'A4', 'A3'],
                 'B': ['B0', 'B1', 'B4', 'B3'],
                 'D': ['D0', 'D1', 'D4', 'D3']},
               index=[0, 1, 2])

我想拥有

    df3 = DataFrame({'A': ['A0', 'A1', 'A3'],
                     'B': ['B0', 'B1', 'B3'],
                     'C': ['C0', 'C1', 'C3'],
                     'D': ['D0', 'D1', 'D3'].
                     index=[0, 1, 2, 3])   

基本上,我合并了2个数据帧,并将列D添加到第一个数据帧.但是我忽略了没有同时包含C和D值的行,例如第2和第4行. 我试过了append和concat,但它只给了我所有的列和所有的行,它们彼此叠放.

Essentially I combine 2 dataframes, adding column D to the first dataframe. But I omit any rows that won't have values for both C and D, like row 2 and 4. I have tried append and concat but it just gives me all the columns and all the rows stacked on top of each other.

谢谢!

推荐答案

只需执行默认的

Just do a default merge this will perform an inner join on common columns:

In [80]:

df1.merge(df2)
Out[80]:
    A   B   C   D
0  A0  B0  C0  D0
1  A1  B1  C1  D1
2  A3  B3  C3  D3

这篇关于合并2个数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆