【问题标题】:Checking if a pandas dataframe column(that has lists as values) has one element of another list检查熊猫数据框列(具有列表作为值)是否具有另一个列表的一个元素
【发布时间】:2021-03-26 02:59:28
【问题描述】:

我有以下名为“files_to_export”的数据框:

|Assignee                                                             |otherColumns...|
["Samsung", "Apple", "Apple Inc."]
["Honda Tech", "Honda Motors", "General Motors", "Huawei"]

我有另一个名为“公司”的列表,其中包含我有兴趣在我的数据中包含的公司,列表结构如下:

 Companies=['Ford','General motors','Mazda',..........]

所以我希望我的数据中的行至少包含我的公司列表中的一家公司(包含我的意思是正则表达式的包含意义,换句话说,如果有一行带有“福特全球技术”,那么我希望它包含在我的数据中,因为它有 Ford 这个词。

我编写了以下代码,但没有捕获任何数据:

output = file_to_export[file_to_export['Assignee'].str.contains('|'.join(companies), case=False, na=False).count(True) > 0]

实际结果是一个空数据帧,输出数据帧中没有行

预期的结果是在输出数据框中有一个包含不同公司行的数据框

有什么建议吗? 感谢您的帮助,我希望我的问题很清楚!

【问题讨论】:

  • 我刚刚编辑了帖子,示例是我试图过滤我的数据帧 files_to_export 的一行代码!

标签: python regex pandas list dataframe


【解决方案1】:

数据设置

files_to_export = pd.DataFrame({'Assignee':[['Samsung','Apple','Apple Inc.'],['Honda Tech','Honda Motors','General Motors']],
                                'other_col':[1,2]})

companies = ['Ford','General motors','Mazda']

# Filter df
# The pattern is a case of or where matching any of the individuals strings will work
pattern = '|'.join(companies) # 'Ford|General motors|Mazda'
# convert the column of lists to a column of comma separated strings
# then check for string containment
files_to_export[files_to_export.Assignee.apply(lambda x: ','.join(x)).str
                .contains(pattern,
                          case=False)]

【讨论】:

  • 此代码生成以下警告:用户警告:此模式具有匹配组。要实际获取组,请使用 str.extract。 return func(self, *args, **kwargs)
  • 我其实看不懂你的模式,为什么要加'()'
  • 括号是group这个词,但这里并不需要。我刚刚编辑了答案,只需加入 | 分隔符,它的运行方式相同,只是没有警告。
猜你喜欢
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 2017-07-15
  • 2020-05-08
  • 2021-08-24
  • 2012-08-01
  • 1970-01-01
  • 2019-05-16
相关资源
最近更新 更多