【问题标题】:Compute the intersection of lists for each pair of values in a column计算列中每对值的列表的交集
【发布时间】:2019-02-08 21:40:30
【问题描述】:

如果我有一个包含 2 列 user_id 和他们的兴趣的数据集,并且我想找到有共同兴趣的用户,我该怎么做?例如,我将第一个用户和他的兴趣单独与所有其他用户的共同兴趣进行比较,然后我将第二个用户将他的兴趣与所有其他用户的兴趣进行比较等等......

我的数据如下:

userid   interest
 1       [A, B]
 2       [A, C, B]
 3       [B, D]

我不知道该怎么做-

for i in range(0,3):
  for j in range(i+1, 3):
    print((df['interest'].loc[i]).intersection(df['interest'].loc[j]))

我的输出应该是-

userid    relativeid  common interest
  1          2           [A, B]
  1          3           [B]
  2          3           [B]

【问题讨论】:

    标签: pandas dataframe combinations


    【解决方案1】:

    使用字典执行查找。然后,您可以使用itertools.combinations 查找“userid”的组合,然后为每个“userid”列表对执行设置交集。

    import itertools
    
    m = df.set_index('userid')['interest'].map(set).to_dict()
    m 
    # {1: {'A', 'B'}, 2: {'A', 'B', 'C'}, 3: {'B', 'D'}}
    
    out = pd.DataFrame(
        itertools.combinations(df.userid, 2), columns=['userid', 'relativeid'])
    out['common_interest'] = [list(m[x] & m[y]) for x, y in out.values]
    out
    
       userid  relativeid common_interest
    0       1           2          [B, A]
    1       1           3             [B]
    2       2           3             [B]
    

    【讨论】:

    • 感谢您的解决方案.....但它给了我一个错误:数据参数不能是迭代器
    • @user11035754 这适用于 0.24。所以你可以尝试pd.DataFrame(list(itertools.combinations(df.userid, 2)), ...)(即将迭代器转换为列表)
    • 这行得通!你能帮我对这段代码再做 2 处修改吗: 1)这段代码给出了一个输出 [], B, A, [, ,] 而不仅仅是 [B,A] ....你能提出一些建议来摆脱那些额外的括号。 2)如果我有单词而不是字母怎么办......像[一,二]
    • @user11035754 df['interest'].values[0] 打印什么?你能告诉我吗?基于此,我可以告诉你修改什么。
    • 它打印这个 - "['one' 'two' 'three' 'four ']"
    【解决方案2】:

    这是我将如何解决的方法,可能有人有更高级的pandas 方式。

    from itertools import combinations
    
    cs = combinations(df.userid.values, 2)
    output = pd.DataFrame(list(cs), columns=['userid', 'relativeid'])
    
    print(output)
    
       userid  relativeid
    0       1           2
    1       1           3
    2       2           3
    
    
    def intersect(row):
        p1 = df.loc[df.userid == row['userid'], 'interest'].values[0]
        p2 = df.loc[df.userid == row['relativeid'], 'interest'].values[0]
        return list(set(p1).intersection(set(p2)))
    
    output.assign(common_interest=output.apply(intersect, axis=1))
    
       userid  relativeid common_interest
    0       1           2          [B, A]
    1       1           3             [B]
    2       2           3             [B]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 2012-11-04
      • 1970-01-01
      相关资源
      最近更新 更多