如何比较具有不同索引的两个数据帧,并打印出重复的行?

时间:2021-06-30 18:37:37

标签: python pandas numpy

我正在尝试按各自的 UniqueID 列比较两个数据框。可以在下面看到以下数据帧的代码。

# Define first dataframe
list1 = {'UniqueID': [13579, 24680, 54678, 1169780, 1195847, 23572],
        'Name': ['Joe', 'Pete', 'Jessica', 'Jackson', 'Griffin', 'Katie'],
        'Level': ['Beginner', 'Beginner', 'Intermediate', 'Advanced', 'Intermediate', 'Advanced']}
df1 = pd.DataFrame(list1, columns=['UniqueID','Name','Level'])

# Define second dataframe
list2 = {'UniqueID': (88922,13579, 24680, 54678, 1169780, 1195847, 23572, 54895, 478952, 45921),
        'Name': ('Zain','Joe', 'Pete', 'Jessica','Griffin','Jackson','Katie', 'Gaby', 'Haley', 'Caden'),
        'Level': ('Beginner', 'Intermediate', 'Intermediate', 'Advanced', 'Intermediate','Advanced','Advanced',
                  'Beginner', 'Intermediate', 'Novice')}
df2 = pd.DataFrame(list2, columns=['UniqueID','Name','Level'])

从上面可以看出,数据帧的索引长度不同。这就是导致我的下一个问题的原因。我查找重复项的过程如下。

# Define new column which displays Match iff the UniqueID of the first dataframe is equal to that of the second
df1['UniqueMatch'] = np.where(df1.UniqueID == df2.UniqueID, 'Match','Ignore') #Create

# Simplify the list to only display rows that are duplicates
df_match = df1[df1['UniqueMatch'] =='Match']

每当我尝试查找数据帧的 UniqueID 在哪里相​​等时,都会遇到错误。我收到的错误是“ValueError:只能比较标记相同的系列对象”。根据我的理解,这意味着我正在使用的过程只有在两个数据帧的索引彼此相等时才能实现。我认为它们必须是解决此问题的方法,如果不是,那么您如何比较不同大小的数据框。

2 个答案:

答案 0 :(得分:1)

df1(5 行)和 df2(9 行)不同——原因:

df1.equals(df2) -> 假


enter image description here


对于打印重复使用那段代码:

df_merge = pd.merge(df1, df2, on=['UniqueID','Name','Level'], how='inner')

您可以定义 - 正确的数据,您想要重复的数据。

例如。 ['Name] & ['Level'](如果你只想在 Name 中重复 - 那个 in 应该只是那个列名。

返回更多重复项:

enter image description here

答案 1 :(得分:1)

更新根据您的评论:

<块引用>

找到重复后,我想遍历级别的每个单元格,并从 df2 中列出的更新级别更新 df1。例如,Joe 从初级到中级,从 df1 到 df2。我想自动更新这些实例。

连接您的 2 个数据框并避免重复的最后一个值 (df2):

df3 = pd.concat([df1, df2], ignore_index=True) \
        .drop_duplicates(['UniqueID', 'Name'], keep='last')
>>> df3
    UniqueID     Name         Level
3    1169780  Jackson      Advanced
4    1195847  Griffin  Intermediate
6      88922     Zain      Beginner
7      13579      Joe  Intermediate  # Joe is now Intermediate
8      24680     Pete  Intermediate  # Pete is now Intermediate
9      54678  Jessica      Advanced  # Jessica is now Advanced
10   1169780  Griffin  Intermediate
11   1195847  Jackson      Advanced
12     23572    Katie      Advanced
13     54895     Gaby      Beginner
14    478952    Haley  Intermediate
15     45921    Caden        Novice

旧答案

使用 mergequery 查找重复项:

dup = pd.merge(df1, df2, on='UniqueID') \
        .query("(Name_x == Name_y) & (Level_x == Level_y)")
>>> dup
   UniqueID Name_x   Level_x Name_y   Level_y
5     23572  Katie  Advanced  Katie  Advanced
相关问题