How do I get all items with which a user was in contact?

Viewed 82

I have a dataframe that has two columns userid and itemid. I would like to select an itemid (for example 715) and get all users who had this itemid. I not only want the users but also all other items that the user has used at the same time. (An example is given below). I have now used isin with the method, it only returns true and false.

How do I manage to get all the items that the user had who had this particular itemid?

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)
print(df)

df2 = df.isin({'itemid': [715]})
print(df2)

    userid  itemid
0        0     715
1        0     845
2        0      98
3        1   12324
4        2      85
5        2     715
6        3    2112
7        3      85
8        4    2112
9        4     852
10       4     102
    userid  itemid
0    False    True
1    False   False
2    False   False
3    False   False
4    False   False
5    False    True
6    False   False
7    False   False
8    False   False
9    False   False
10   False   False

What I want

    userid  itemid
0        0     715
1        0     845
2        0      98
4        2      85
5        2     715
3 Answers

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

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

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
Related