通过从熊猫的数据框中排除某些代码来过滤数据

时间:2020-04-24 20:33:24

标签: python pandas

这是我的数据框:

    employee_code      eligible_date**
         student   
         student   
         trainee   
         trainee            2020-05-29
         employee           2020-05-06  
         employee   
         employee           2020-07-01  

我想要做的是从我的数据集中排除学生和受训者。

    data = data[((data.employee_code == "student") | (data.employee_code == "trainee")) & (data.eligible_date.isnull())]

我的代码在这里相反,只包含它们。有没有简单的方法可以更改上面的代码以排除它们?

谢谢。

3 个答案:

答案 0 :(得分:1)

使用query,更易于阅读:

filter = ['student', 'trainee']
data = data.query('employee_code not in @filter')

答案 1 :(得分:1)

我会布尔选择学生和受训者,然后反转选择。更快,更整齐

m=df['employee_code'].isin(['student','trainee'])
df[~m].dropna()

输出

enter image description here

或者

m=(df['employee_code'].isin(['student','trainee']))|(df.eligible_date.isnull())
m
df[~m]#.dropna()

答案 2 :(得分:1)

data = data[~(data['employee_code'].str.contains('student|trainee')&
              data['eligible_date'].isnull())]