分组后按两个条件过滤

时间:2018-07-05 14:33:05

标签: python pandas

我愿意在type列中以及每当login_method等于resend时过滤具有SMS和电话的ID。

df

id    type   login_method
 1     SMS         resend
 1     SMS       complete
 2   phone         resend
 2     SMS         resend
 2     SMS          start
 3   phone         resend
 3   phone          start
 3   phone       complete
 3     SMS           nice

预期结果

df
    id    type   login_method
 1     SMS         resend
 1     SMS       complete
 3   phone         resend
 3   phone          start
 3   phone       complete
 3     SMS           nice

在这种情况下,只有id 2的电话和短信的登录方式等于重新发送

1 个答案:

答案 0 :(得分:1)

使用:

v = ['SMS','phone']
#first filter only valuse by list
df = df[df['type'].isin(v)]

#get id where are all values per groups with resend
m1 = df['login_method'] == 'resend'
s = df[m1].drop_duplicates(['id','type']).groupby('id')['type'].nunique() != len(v)

#filtering by ids
df1 = df[df['id'].isin(s.index[s])]
print (df1)
   id   type login_method
0   1    SMS       resend
1   1    SMS     complete
4   3  phone       resend
5   3  phone        start
6   3  phone     complete
7   3    SMS         nice
相关问题