How do I get all items with which a user was in contact?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC E Schuberts Piano Sonata D 784 in A
--
Chapters
00:00 Question
01:17 Accepted answer (Score 2)
01:56 Answer 2 (Score 3)
02:16 Answer 3 (Score 2)
02:32 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
--
Track title: CC E Schuberts Piano Sonata D 784 in A
--
Chapters
00:00 Question
01:17 Accepted answer (Score 2)
01:56 Answer 2 (Score 3)
02:16 Answer 3 (Score 2)
02:32 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