【问题标题】:Filter a 2 columns of a DataFrame using a dictionary containing lists Python使用包含列表 Python 的字典过滤 DataFrame 的 2 列
【发布时间】:2020-09-22 02:00:42
【问题描述】:

我有一个 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

我不知道该怎么做?

【问题讨论】:

  • 您能否分享一个具有预期输出的数据框样本?
  • 类似df[df[key] in val for key, val in departments.iteritems()]?
  • 刚刚添加了我正在寻找的示例
  • 另外,Datanovice,如果我只想过滤一组级别,那将起作用。我的字典中可能有 20 项需要用作过滤器。所以 20 个部门,每个部门都有大约 4 个级别我要过滤。
  • 对不起菲尔我只在编辑后看到了你的数据框,我的假设是基于你的字典。

标签: python pandas dataframe dictionary


【解决方案1】:

您可以在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

【讨论】:

  • 很好的答案,我在想如何以矢量化的方式做到这一点。在 SQL 中,我将通过连接 Department 和 Level 创建一个临时列,并对 dict 执行相同操作,然后应用一个 in 子句。不确定这是否会比 groupby 应用更快
  • 这看起来很棒!我现在只是在做一些测试,以确保我得到了我期望的结果。
  • @Ben.T,您认为它是否适用于其他类别,例如部门 > 级别 > 位置?
  • @Ben.T 道歉!没看到,我现在在聊天中回复。谢谢!
猜你喜欢
  • 2021-02-15
  • 2018-01-06
  • 2021-10-04
  • 2022-10-13
  • 2015-12-22
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多