如果在列中找到搜索项目,我需要从数据帧中进行筛选(例如,用搜索到的专业领域识别所有员工的empID
import pandas as pd
date=[
[123,['abc','def','efg']],
[124,['abc','qwe','mno']],
[124,['abc','qwe','mno']],
[126,['wer','abc']]
]
expertise_df=pd.DataFrame(date,columns=['EmpId','areas'])
我希望筛选具有"abc"或"qwe"等的行,但不需要在所有行中显式创建循环并检查匹配。我尝试了experise_df[‘reas’.str.contains,但没有返回结果。这将在experise_df中的200000行上匹配大约1000个搜索字符串,因此寻找时间有效的方法。蛮力方法需要4个多小时,不实用的
此外,如果我需要创建并集运算(包含"abc"或"pqr"等(,有没有办法将结果作为集来处理?
如果要检查多个值(例如['def', 'wer']
(,可以使用isdisjoint中apply的否定。
mask = ~expertise_df['areas'].apply(frozenset(['def', 'wer']).isdisjoint)
res = expertise_df[mask]
print(res)
输出
EmpId areas
0 123 [abc, def, efg]
3 126 [wer, abc]
要筛选包含qwe
作为expertise_df
第二列中列表元素的行,可以执行:
expertise_df[
pd.DataFrame(
expertise_df.explode('areas')
['areas'].str.contains('qwe'))
.reset_index()
.groupby('index')
.any()['areas']]
这将给你:
EmpId areas
1 124 [abc, qwe, mno]
2 124 [abc, qwe, mno]
如果要查找包含列表任一元素的行,即:
searchfor = ['wer','def']
然后使用"如何过滤Pandas数据帧中包含字符串模式的行:">
expertise_df[
pd.DataFrame(
expertise_df.explode('areas')
['areas'].str.contains('|'.join(searchfor)))
.reset_index()
.groupby('index')
.any()['areas']]
您可以使用set交集来过滤所需的行。
import pandas as pd
date=[
[123,['abc','def','efg']],
[124,['abc','qwe','mno']],
[124,['abc','qwe','mno']],
[126,['wer','abc']]
]
expertise_df=pd.DataFrame(date,columns = ['EmpId','areas'])
filter_set = {'def','wer'}
filtered_df=expertise_df[expertise_df['areas'].
apply(lambda el: bool(filter_set.intersection(el)))]
print(filtered_df)
输出:
EmpId areas
0 123 [abc, def, efg]
3 126 [wer, abc]