一条语句中的多个isin查询

时间:2018-10-19 07:19:44

标签: python pandas

我有一个数据帧df,其头部看起来像:

id      dept       paid
97   accounts   monthly
73       shop    weekly
20  marketing    yearly
70   analysis   monthly
55   advisory   monthly
42  marketing   monthly
76  marketing    weekly

我感兴趣的是从部门的子集和带薪的子集中查看一部分员工。

例如,如果我想返回数据帧的子集marketingadvisory,而其中仅返回付费的monthlyweekly

我将返回以下完整记录:

id       dept      paid
55   advisory   monthly
42  marketing   monthly
76  marketing    weekly

我尝试使用两个名为deptQuery和paidQuery的列表,它们看起来像:

deptQuery = ['marketing','advisory']

paidQuery = ['monthly','weekly']

并将其应用于:

queryResult = df[df['dept'].isin(deptQuery) and DeptTemplate['paid'].isin(paidQuery)] 

我也尝试过

queryResult = df[df['dept'].isin(deptQuery)] and df[df['paid'].isin(paidQuery)]

但是我无法正常工作。有人可以提供一些帮助吗?

非常感谢

1 个答案:

答案 0 :(得分:4)

将&用于按位AND,然后删除df[

queryResult = df[df['dept'].isin(deptQuery) & df['paid'].isin(paidQuery)]

print (queryResult)
   id       dept     paid
4  55   advisory  monthly
5  42  marketing  monthly
6  76  marketing   weekly

使用query的另一种解决方案:

queryResult = df.query('dept in @deptQuery & paid in @paidQuery')