比较两个 pandas 数据框 [英] compare two pandas data frame

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

问题描述

我有两个这样定义的熊猫数据框:

I have two pandas dataframes defined as such:

_data_orig = [
    [1, "Bob", 3.0],
    [2, "Sam", 2.0],
    [3, "Jane", 4.0]
]
_columns = ["ID", "Name", "GPA"]

_data_new = [
        [1, "Bob", 3.2],
        [3, "Jane", 3.9],
        [4, "John", 1.2],
        [5, "Lisa", 2.2]
    ]
_columns = ["ID", "Name", "GPA"]

df1 = pd.DataFrame(data=_data_orig, columns=_columns)
df2 = pd.DataFrame(data=_data_new, columns=_columns)

我需要找到以下信息:

  • 查找删除df1是原始数据集,而df2是新数据集
  • 我需要找到两者之间现有记录的行更改.示例ID == 1应该比较df2的ID == 1,以查看是否每一行的列值都发生了更改.
  • 找到df2和df1的所有加法.示例返回[4,"John",1.2]和[5,"Lisa",2.2]

对于查找行中更改的操作,我认为可以浏览df2并检查df1,但这似乎很慢,所以我希望在那里找到一个更快的解决方案.

For operation to find changes in rows, I figured I could look through df2 and check df1, but that seems slow, so I'm hoping to find a faster solution there.

对于其他两个操作,我真的不知道该怎么做,因为当我尝试比较两个数据帧时,我会得到:

For the other two operations, I really do not know what to do because when I try to compare the two dataframes I get:

ValueError: Can only compare identically-labeled DataFrame objects

熊猫版本:"0.16.1"

Pandas version: '0.16.1'

建议?

推荐答案

设置

setup

m = df1.merge(df2, on=['ID', 'Name'], how='outer', suffixes=['', '_'], indicator=True)
m

添加

adds

m.loc[m._merge.eq('right_only')]

m.query('_merge == "right_only"')

m.loc[m._merge.eq('right_only')]
or
m.query('_merge == "right_only"')

删除

deletes

m.loc[m._merge.eq('left_only')]

m.query('_merge == "left_only"')

m.loc[m._merge.eq('left_only')]
or
m.query('_merge == "left_only"')

0.16.1答案

设置

setup

m = df1.merge(df2, on=['ID', 'Name'], how='outer', suffixes=['', '_'])
m

添加

adds

m.loc[m.GPA_.notnull() & m.GPA.isnull()]

删除

deletes

m.loc[m.GPA_.isnull() & m.GPA.notnull()]

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

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