我有一个雇员的 pandas 数据框,我需要根据 2 列进行过滤。我需要过滤部门和级别。假设我们有“人力资源”部门,其中有 1、2、3、4、5 级。我正在专门寻找 2、4 和 5 级人力资源。
我有我想要的部门和级别存储在字典中,例如:
departments = dict({'Human Resources' : ['2','4','5'] ,'IT' : ['1','3','5','6'], etc.... })
我的数据框将列出所有部门和所有级别(以及更多)的每位员工。我现在想使用上面的字典过滤该数据框。因此,在人力资源示例中,我只想返回“人力资源”中第 2、4 和 5 级的员工。
df 的一个例子是:
employee_ID Department Level
001 Human Resources 1
002 Human Resources 1
003 Human Resources 2
004 Human Resources 3
005 Human Resources 4
006 Human Resources 4
007 Human Resources 5
008 IT 1
009 IT 2
010 IT 3
011 IT 4
012 IT 5
013 IT 6
使用上面显示的字典,我的预期结果是
employee_ID Department Level
003 Human Resources 2
005 Human Resources 4
006 Human Resources 4
007 Human Resources 5
008 IT 1
010 IT 3
012 IT 5
013 IT 6
我不知道该怎么做?
最佳答案
可以在Departement上使用groupby
,在Level上使用isin
,获取与组名称相关的部门的值。
#example data
departments = dict({'Human Resources' : ['2','4','5'] ,'IT' : ['1','3','5','6']})
df = pd.DataFrame({'Id':range(10),
'Departement': ['Human Resources']*5+['IT']*5,
'Level':list(range(1,6))*2})
#filter
print (df[df.groupby('Departement')['Level']
.apply(lambda x: x.isin(departments[x.name]))])
Id Departement Level
1 1 Human Resources 2
3 3 Human Resources 4
4 4 Human Resources 5
5 5 IT 1
7 7 IT 3
9 9 IT 5
关于python - 使用包含列表 Python 的字典过滤 DataFrame 的 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62171693/