I'm trying to create a df that contains the number of users that rated rated both movies from a pair for every pair of movies.
My original df
df = pd.DataFrame({'index': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6}, 'userID': {0: 1, 1: 2, 2: 2, 3: 3, 4: 3, 5: 1, 6: 2}, 'MovieID': {0: 0, 1: 1, 2: 0, 3: 2, 4: 1, 5: 1, 6: 2}, 'rating': {0: 4, 1: 1, 2: 3, 3: 2, 4: 2, 5: 2, 6: 3}})
which looks like:
| index | userID | MovieID | rating |
|---|---|---|---|
| 0 | 1 | 0 | 4 |
| 1 | 2 | 1 | 1 |
| 2 | 2 | 0 | 3 |
| 3 | 3 | 2 | 2 |
| 4 | 3 | 1 | 2 |
| 5 | 1 | 1 | 2 |
| 6 | 2 | 2 | 3 |
What i want to achieve
| movieID / movieID | 0 | 1 | 2 |
|---|---|---|---|
| 0 | nan | 2 | 1 |
| 1 | 2 | nan | 2 |
| 2 | 1 | 2 | nan |
Currently I'm computing this df iteratively; for each unique combination of movieID's, and passing the ids to this function
def foo(id1, id2):
id1_users = set(df[df["movieID"] == id1]["userID"].to_list())
id2_users = set(df[df["movieID"] == id2]["userID"].to_list())
combined = len(id1_users & id2_users)
return combined
Is there a faster way to compute this?