The Python Oracle

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: Horror Game Menu Looping

--

Chapters
00:00 How Do I Get All Items With Which A User Was In Contact?
00:38 Answer 1 Score 3
00:54 Answer 2 Score 2
01:06 Accepted Answer Score 2
01:26 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