简体   繁体   中英

How to return rows for a specific condition that involves two columns in Pandas?

I have this dataframe:

user_id     status_id       date_created
1           1               2018-02-14 11:49:07.429000-02:00
1           4               2018-02-19 12:51:43.622000-03:00
1           3               2018-02-15 09:21:23.116000-02:00
2           3               2018-02-19 12:52:08.646000-03:00
3           3               2016-08-29 11:02:39.449000-03:00
4           4               2016-08-29 11:18:31.742000-03:00
4           2               2018-02-21 10:43:45.747000-03:00
5           3               2018-02-15 09:34:57.478000-02:00
5           2               2018-02-19 11:52:16.629000-03:00

I want to return only users that has a specific status_id and only this specific status, so for example, for status_id=3 , it should return this:

user_id     status_id       date_created
2           3               2018-02-19 12:52:08.646000-03:00
3           3               2016-08-29 11:02:39.449000-03:00

I tried filtering all users that have the status_id that I need, but it also returns users with more than one status_id :

> df.loc[df.user_id.isin(df.user_id.loc[df.status_id == 3])]
user_id     status_id       date_created
1           1               2018-02-14 11:49:07.429000-02:00
1           4               2018-02-19 12:51:43.622000-03:00
1           3               2018-02-15 09:21:23.116000-02:00
2           3               2018-02-19 12:52:08.646000-03:00
3           3               2016-08-29 11:02:39.449000-03:00
5           3               2018-02-15 09:34:57.478000-02:00
5           2               2018-02-19 11:52:16.629000-03:00

By using transform + nunique

df[df.groupby('user_id').status_id.transform('nunique').eq(1)].loc[lambda x :x['status_id']==3,:]

More Info

df.groupby('user_id').status_id.transform('nunique') # get the number of unique value within each group, after this we just need to select the group only contain one value , which is index 3,4
Out[426]: 
0    3
1    3
2    3
3    1
4    1
5    2
6    2
7    2
8    2
Name: status_id, dtype: int64

You can use df.loc[df['status_id'] == 3] as described here

Python File with relevant input

Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM