【问题标题】:Comparing x amount of tuples and printing out duplicates比较 x 数量的元组并打印出重复项
【发布时间】:2021-07-27 23:52:59
【问题描述】:

我有一个数据框,其中一列包含一个长度不同的元组列表,这些元组代表产品代码,每个合同号都是索引。元组的长度在 1 到 22 之间变化。我使用groupby() 对相同长度的元组进行分组。

我使用df.get_group() 来访问每个长度的数据帧。每个 df 的行数从 1 到 80 不等。

例如对于元组 (123, 456, 789) 和 (123, 456, 213),我希望输出为: [1]: (123, 456)

从这里我想将每个元组与数据框中其他元组的 x 数量进行比较,并打印出所有重复项。

我尝试过使用set(x) & set(y),但我不确定如何将它用于 x 行。

有没有更 Pythonic 的方式来做到这一点?

【问题讨论】:

    标签: python pandas dataframe duplicates tuples


    【解决方案1】:

    让我们尝试将一个组中的所有元组合并为一个系列,并使用duplicated 抓取重复项:

    import pandas as pd
    
    df = pd.DataFrame({'tuples': [(136, 629, 694), (136, 273, 208),
                                  (640, 139, 405, 884, 734),
                                  (123, 456, 789),
                                  (492, 829, 451, 315, 804),
                                  (123, 456, 213), (142, 569, 636, 380),
                                  (924, 808, 330, 489, 658),
                                  (538, 163, 669, 817), (569, 780),
                                  (230, 569), (278, 509, 718, 817)]})
    
    
    def get_duplicates(s):
        # Convert Tuples into a Series
        s = pd.Series(s.sum())
        # Filter duplicated and convert back to tuple
        return tuple(s[s.duplicated()])
    
    
    # Groupby len and apply function
    duplicate_tuples = df.groupby(
        df['tuples'].map(len)
    )['tuples'].apply(get_duplicates).reset_index(name='duplicate_values')
    
    # For Display
    print(duplicate_tuples.to_string(index=False))
    

    输出:

    tuples duplicate_values
         2           (569,)
         3  (136, 123, 456)
         4           (817,)
         5               ()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-12-16
      • 2017-12-31
      相关资源
      最近更新 更多