检查dataframe列(将列表作为值)是否具有另一个列表的一个元素

2024-04-29 20:06:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下称为“文件到导出”的数据帧:

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

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

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

因此,我希望数据中的行在我的公司列表中至少包含一家公司(所谓包含,我指的是regex意义上的包含,换句话说,如果有一行带有“Ford global tech”,那么我希望它包含在我的数据中,因为它有一个单词Ford

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

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

实际结果是输出数据帧中没有行的空数据帧

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

有什么建议吗? 谢谢你的帮助,我希望我的问题是清楚的


Tags: 文件to数据falseapple列表公司export
1条回答
网友
1楼 · 发布于 2024-04-29 20:06:35

数据的设置

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)]

相关问题 更多 >