【问题标题】:Selecting rows in dataframe where a value is larger than the categorical mean在数据框中选择值大于分类平均值的行
【发布时间】:2021-12-02 04:42:33
【问题描述】:

我正在努力寻找工资高于部门平均工资的员工,但我在 Pandas 中遇到了一些麻烦。

在 SQL 中,我的查询如下所示:

SELECT name, department, salary
FROM employees e1
WHERE salary > (SELECT AVG(salary) FROM employees e2 WHERE e1.department = e2.department)

这是我在 Pandas 中的尝试:

df.groupby(['Department']).filter(lambda x: df['salary'] > x.salary.mean())[['Name', 'Salary']]

我收到以下错误,我假设它来自过滤器子句中的 df['salary']:

过滤器函数返回一个系列,但需要一个标量布尔

【问题讨论】:

  • df.loc[df["Salary"]>df.groupby("Department")["Salary"].transform("mean")]?

标签: python sql pandas dataframe filtering


【解决方案1】:

这不像我想要的那样可读,但我认为它有效:

import pandas as pd
df = pd.DataFrame(columns=['employees', 'department', 'salary', 'other_features'],
      data=[['A', 'C1', 1300, 5], 
            ['B', 'C1', 1250, 10], 
            ['C', 'C1', 2000, 18],
            ['D', 'C3', 1240, 21], 
            ['E', 'C1', 1700, 29],
            ['F', 'C2', 1550, 11],
            ['G', 'C3', 2100, 2],
            ['H', 'C3', 1090, 7],
            ['I', 'C2', 1400, 13],
            ['B', 'C2', 1100, 4]])



df.set_index('employees').groupby('department').apply(lambda x: x[x.salary > x.salary.mean()])['salary']

output:

             employees  salary
department          
C1             C         2000
               E         1700
C2             F         1550
               I         1400
C3             G         2100

【讨论】:

    猜你喜欢
    • 2013-10-30
    • 2020-01-23
    • 2020-09-15
    • 2013-02-14
    • 2016-09-04
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 2022-01-18
    相关资源
    最近更新 更多