【问题标题】:pandas duplicated records find same and different columns熊猫重复记录找到相同和不同的列
【发布时间】:2017-05-24 03:19:27
【问题描述】:

我有这样的记录

raw_data = {
        'subject_id': ['1', '2', '2', '3', '3'],
        'name': ['A', 'B', 'B', 'C', 'D'],
        'age_group' : [1, 2, 2, 1, 1]}
df = pd.DataFrame(raw_data, columns = ['subject_id', 'name','age_group'])

其中包含一个(重复的)ID 和一些额外的列。下面

ids = df.subject_id
df[ids.isin(ids[ids.duplicated()])]

将只返回重复的记录。现在我想更好地理解

  • 一样
  • 不同

对于每个重复的记录,即在这种情况下,我希望接收有问题的重复 ID 以及行不同的相应列。

  subject_id name
1          2    B
2          2    B
3          3    C
4          3    D

【问题讨论】:

  • 你能举一个你正在寻找的输出的例子吗?
  • 不是已经包含了吗?我正在按 Id 查找重复的行,并且只想查看值不同的列
  • 我认为我的困惑来自于查看subject_id == 2,其中age_group 不同但不包括在内,而您确实有name,这对于这些行没有区别。
  • 我看到 - 更新了示例。

标签: python pandas duplicates


【解决方案1】:

如果你有

>>>duplicated_ids
  subject_id name  age_group
1          2    B          2
2          2    B          2
3          3    C          1
4          3    D          1

然后

>>>othercols = duplicated_ids.columns[1:]
>>>outcols = ['subject_id']
>>>for col in othercols:
       if not duplicated_ids.drop_duplicates(['subject_id', col], keep=False).empty:
           outcols.append(col)

>>>duplicated_ids.loc[:, outcols]
  subject_id name
1          2    B
2          2    B
3          3    C
4          3    D

【讨论】:

    【解决方案2】:

    这是一种方法,可以探索和更好地了解差异发生的地方。

    我们将设置一个列,表明我们发现了一个行,其中给定的subject_id 与我们之前为他们的name 或他们的age_group 记录的不匹配,即我们发现了差异。此列将称为diff_indicator,如果与先前记录的值没有不同,则为二进制0,如果不同,则为1

    storage_dict = {}
    
    
    for i in range(len(df)):
        if not df.loc[i, 'subject_id'] in storage_dict:
            storage_dict[df.loc[i, 'subject_id']] = (df.loc[i, 'name'], df.loc[i, 'age_group'])
    for i in range(len(df)):
        if (df.loc[i, 'name'] != storage_dict[df.loc[i, 'subject_id']][0]) | \
        (df.loc[i, 'age_group'] != storage_dict[df.loc[i, 'subject_id']][1]):
            df.loc[i, 'diff_indicator'] = 1
        else:
            df.loc[i, 'diff_indicator'] = 0
    

    从这里我们可以探索存在差异的地方。

    >>> df.loc[df['diff_indicator'] == 1]['subject_id'].unique()
    array(['2', '3'], dtype=object)
    
    >>> df.loc[df['diff_indicator'] == 1]
      subject_id name  age_group  diff_indicator
    2          2    B          1             1.0
    4          3    D          1             1.0
    

    根据您的兴趣,有多种查询方法。我们可以像这样返回所需的输出...

    >>> df.loc[df['subject_id'].isin(df.loc[df['diff_indicator'] == 1]['subject_id'].unique())]
      subject_id name  age_group  diff_indicator
    1          2    B          2             0.0
    2          2    B          1             1.0
    3          3    C          3             0.0
    4          3    D          1             1.0
    

    我们可以看到这个数据框的前两列是期望的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-30
      • 2019-03-15
      • 1970-01-01
      • 2019-02-18
      • 2021-01-15
      • 2022-10-31
      • 1970-01-01
      • 2017-03-26
      相关资源
      最近更新 更多