【问题标题】:Pandas - column of list values (str type) - find matches with any element of another list (also str type)Pandas - 列表值列(str 类型) - 查找与另一个列表的任何元素(也是 str 类型)的匹配项
【发布时间】:2021-10-25 16:11:47
【问题描述】:

我有以下 Pandas df,名为 pro

    property    name
0   too         Deliveroo
1   bar         Gousto
2   baz         Gousto
3   foobar      Deliveroo
4   too         Gousto
5   foobaz      Deliveroo

应用以下代码时:

property = pro.groupby('name')['property'].apply(list).reset_index(name='property')

我得到 属性 df:

    name        property
0   Deliveroo   [too,foobar,foobaz]
1   Gousto      [bar,baz,too]

我想检查列表中的元素是否与property['property'] 列中的任何列表匹配,例如

check = ['bar']应该在df的第1行找到“bar”。

check = ['bar','baz']应该在df的第1行找到“bar”和“baz”。

check = ['too'] 应该在 df 的第 0 行和第 1 行找到“too”。

check = ['foobar']应该在df的第0行找到“foobar”。

我知道我可以循环遍历 property['property'] 中的所有项目(它们是列表类型)并使用 check 列表来处理它们,但我想使用高效的 Pandas 方法来做到这一点。我试过.isin,但在这种情况下我不能让它工作。

最终结果应该允许使用check 列表来过滤property df。

【问题讨论】:

  • 请添加您的预期输出

标签: python pandas string list dataframe


【解决方案1】:

您可以使用set,然后找到数据框值与列表的交集:

>>> prop = pro.groupby('name')['property'].apply(list).reset_index(name='property')
>>> prop['property'].apply(lambda x: set(x).intersection(['bar']))
0       {}
1    {bar}
Name: property, dtype: object

>>> prop['property'].apply(lambda x: set(x).intersection(['bar', 'baz']))
0            {}
1    {baz, bar}
Name: property, dtype: object

>>> prop['property'].apply(lambda x: set(x).intersection(['too']))
0    {too}
1    {too}
Name: property, dtype: object

使用set 时可能无法维持订单,但我认为这不是问题所在。如果在将这些值分组后将它们转换为set,而不是转换为列表,那就更好了。

附带说明,不要将property 用作变量名,它是用于定义类的属性属性的包装器。

【讨论】:

  • 您好,我还不能投票,但您的解决方案提供了一个很好的起点。另外,感谢您了解使用属性作为变量名的危险
猜你喜欢
  • 1970-01-01
  • 2018-03-11
  • 2019-01-05
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
  • 1970-01-01
  • 2019-03-02
相关资源
最近更新 更多