【问题标题】:Pandas: How do I see the overlap between two lists in a dataframe?Pandas:如何查看数据框中两个列表之间的重叠?
【发布时间】:2023-01-11 03:27:15
【问题描述】:

我有一个包含两列的数据框,每列都包含列表。我想确定两列列表之间的重叠。

例如:

df = pd.DataFrame({'one':[['a', 'b', 'c'], ['d', 'e', 'f'], ['h', 'i', 'j']], 
                   'two':[['b', 'c', 'd'], ['f', 'g', 'h',], ['l', 'm', 'n']]})
        one         two
    0   [a, b, c]   [b, c, d]
    1   [d, e, f]   [f, g, h]
    2   [h, i, j]   [l, m, n]

最终,我希望它看起来像:

        one         two             overlap
    0   [a, b, c]   [b, c, d]       [b, c]
    1   [d, e, f]   [f, g, h]       [f]
    2   [h, i, j]   [l, m, n]       []

【问题讨论】:

    标签: pandas list overlap


    【解决方案1】:

    没有有效的矢量方法来执行此操作,最快的方法是使用 set 交集进行列表理解:

    df['overlap'] = [list(set(a)&set(b)) for a,b in zip(df['one'], df['two'])]
    

    输出:

             one        two overlap
    0  [a, b, c]  [b, c, d]  [b, c]
    1  [d, e, f]  [f, g, h]     [f]
    2  [h, i, j]  [l, m, n]      []
    

    【讨论】:

      【解决方案2】:

      这样做的熊猫方式可能是这样的 -

      df['overlap'] = df.apply(lambda x: list(set(x['one']).intersection(x['two'])),1)
      print(df)
      
               one        two overlap
      0  [a, b, c]  [b, c, d]  [b, c]
      1  [d, e, f]  [f, g, h]     [f]
      2  [h, i, j]  [l, m, n]      []
      

      【讨论】:

        猜你喜欢
        • 2019-02-06
        • 1970-01-01
        • 1970-01-01
        • 2022-11-22
        • 1970-01-01
        • 2014-12-03
        • 2013-08-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多