python - 使用包含列表 Python 的字典过滤 DataFrame 的 2 列

标签 python pandas dataframe dictionary

我有一个雇员的 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/

相关文章:

python-3.x - 基于不同列值的条件语句

python - 如何每第 4 行将列总数附加到 Pandas 数据框?

python - 为 Pandas 数据框中的每个现有变量从行创建新变量

python - 如何使用 df.replace(key :value) inside for loop in python

python - 继承时更改文档字符串但保留方法相同

python - Pandas+Python - 如何知道值何时发生变化?

python - 使用 Pandas Align 时,时间序列数据帧返回错误 - valueError : cannot join with no overlapping index names

python - Pandas 数据框作为 matplotlib.pyplot.boxplot 的输入

python - 安全删除内存中的密码(Python)

python - 无法正确增加 "Minesweeper"的数组元素