How do I get all items with which a user was in contact?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 How Do I Get All Items With Which A User Was In Contact?
01:04 Answer 1 Score 3
01:25 Answer 2 Score 2
01:41 Accepted Answer Score 2
02:14 Thank you
--
Full question
https://stackoverflow.com/questions/6526...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping
--
Chapters
00:00 How Do I Get All Items With Which A User Was In Contact?
01:04 Answer 1 Score 3
01:25 Answer 2 Score 2
01:41 Accepted Answer Score 2
02:14 Thank you
--
Full question
https://stackoverflow.com/questions/6526...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #pandas #dataframe
#avk47
ANSWER 1
Score 3
You could use isin twice - First to get users associated with 715, the second isin is to filter for those users:
users = df.loc[df.itemid == 715, "userid"]
df.loc[df.userid.isin(users)]
userid itemid
0 0 715
1 0 845
2 0 98
4 2 85
5 2 715
ANSWER 2
Score 2
Do this:
In [450]: x = df[df.itemid.eq(715)].userid.unique()
In [452]: df[df.userid.isin(x)]
Out[452]:
userid itemid
0 0 715
1 0 845
2 0 98
4 2 85
5 2 715
ACCEPTED ANSWER
Score 2
In just ONE line of code.
Data:
d = {'userid': [0, 0, 0, 1, 2, 2, 3, 3, 4, 4, 4],
'itemid': [715, 845, 98, 12324, 85, 715, 2112, 85, 2112, 852, 102]}
df = pd.DataFrame(data=d)
df.head(7): # first 7 rows
userid itemid
0 0 715
1 0 845
2 0 98
3 1 12324
4 2 85
5 2 715
6 3 2112
df[df.userid.isin(df[df.itemid==715].userid)]
userid itemid
0 0 715
1 0 845
2 0 98
4 2 85
5 2 715