【问题标题】:Pandas .isin on column entries containing lists包含列表的列条目上的 Pandas .isin
【发布时间】:2019-08-22 05:41:05
【问题描述】:

我正在尝试使用 isin() 函数通过传入一个列表并与也包含列表的数据框列进行比较来过滤数据框。这是以下问题的扩展:

How to implement 'in' and 'not in' for Pandas dataframe

例如,现在每一行都包含一个国家列表,而不是每行一个国家/地区。

df = pd.DataFrame({'countries':[['US', 'UK'], ['UK'], ['Germany', 'France'], ['China']]})

为了过滤,我设置了两个单独的列表:

countries = ['UK','US']
countries_2 = ['UK']

预期结果应该相同,因为第 0 行和第 1 行都包含英国和/或美国

>>> df[df.countries.isin(countries)]
  countries
0     US, UK
1         UK
>>> df[~df.countries.isin(countries_2)]
  countries
0     US, UK
1         UK

然而 Python 抛出了以下错误

TypeError: unhashable type: 'list'

【问题讨论】:

  • 您的数据框代码在语法上不正确
  • 谢谢你,@jezrael 修复它

标签: python pandas dataframe


【解决方案1】:

使用集合和issubsetisdisjointmap 的一种可能解决方案:

print (df[df.countries.map(set(countries).issubset)])
  countries
0  [US, UK]

print (df[~df.countries.map(set(countries).isdisjoint)])
  countries
0  [US, UK]
1      [UK]

print (df[df.countries.map(set(countries_2).issubset)])
  countries
0  [US, UK]
1      [UK]

print (df[~df.countries.map(set(countries_2).isdisjoint)])
  countries
0  [US, UK]
1      [UK]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 2018-07-07
    • 2017-10-22
    • 1970-01-01
    • 2018-10-25
    • 2018-12-10
    • 2021-12-03
    • 2019-02-20
    相关资源
    最近更新 更多