【问题标题】:Extract to a new dataset the equal tuples of a column of tuples in python将python中一列元组的相等元组提取到新数据集
【发布时间】:2020-06-28 17:18:07
【问题描述】:

我有一个dataFrame,它以id 上的userid 访问列表开头,具有userid's 的元组,这些元组针对给定的id 重复。它还有这个元组重复的次数,像这样:

    id  id2 duplicates
0   a   b   [((us1, us2), 5), ((us2, us1), 3), ((us2, us4), 2)]
9   c   b   [((us1, us2), 5), ((us2, us1), 3), ((us2, us4), 2)]

所以在第一行,元组 (us1, us2) 出现了 5 次

生成这个的代码在这里:

d = {'id': ["a", "a", "a", "a", "a", "a", "a", "a", "a", "c", "c", "c", "c", "c"], 
     'id2': ["b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b", "b"], 
     'userid': ["us1", "us2", "us1", "us2", "us4", "us4", "us5", "us1", "us2", "us1", "us2", "us1", "us2", "us4"],
     "time": [1, 2, 3, 5, 4, 7, 6, 8, 9, 10, 11, 12, 13, 14]}

    df_test = pd.DataFrame(data=d).sort_values('time')
    df_test.groupby(['id','id2']).agg(lambda x: x.tolist()).reset_index()
    df_test['tuples']=  df_test.apply(lambda x: list(zip(df_test.userid[:-1].sort_index(), df_test.userid[1:].sort_index())), 1)
    df_test = df_test.drop_duplicates(['id'],keep='first').drop(['userid', 'time'], 1)
    df_test['duplicates'] = df_test.apply(lambda x: [(k,v) for k,v in Counter(x.tuples).items() if v>1], 1)
    df_test.drop('tuples',1)

我现在需要并且我不管理操作方法是找到在具有相同id2 但不同id 的不同行中重复的元组(在列重复项上),所以这里的结果应该成为一个新的数据框:

id     id2  duplicates
[a, c]  b   [(us1, us2), (us2, us1), (us2, us4)]

【问题讨论】:

    标签: python-3.x pandas tuples


    【解决方案1】:

    使用explode更改您的代码

    df_test = pd.DataFrame(data=d).sort_values('time')
    df_test.groupby(['id', 'id2']).agg(lambda x: x.tolist()).reset_index()
    df_test['tuples'] = df_test.apply(
         lambda x: list(zip(df_test.userid[:-1].sort_index(), df_test.userid[1:].sort_index())), 1)
    s=df_test.explode('tuples').groupby(['tuples','id2']).id.apply(pd.Series.unique).apply(tuple).reset_index()
    s.groupby(['id','id2']).tuples.agg(list)
    id      id2
    (a, c)  b      [(us1, us2), (us2, us1), (us2, us4), (us4, us4...
    Name: tuples, dtype: object
    

    【讨论】:

      猜你喜欢
      • 2020-01-09
      • 2013-05-21
      • 2011-10-15
      • 1970-01-01
      • 2017-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多