Get the most bought top 10 items as a list

Viewed 759

I want to get the most bought items in a list. But at the moment I got only the counts of the number. How do I get the itemids ?

I want the list like the following [element 1, element 2, ...,element n-1, element n]. How do I get the top 10 most bought items?

How do I get most of the items I have bought? By counting how often the itemid occurs, the id that occurs the most is the item bought most often.

import pandas as pd
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.head(10))

df_new = df.groupby('itemid').count().head(10) # get the top 10 products
print(df_new)

print(df_new.values.tolist())

Now the output

# the dataframe
   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

# the counts
        userid
itemid        
85           2
98           1
102          1
715          2
845          1
852          1
2112         2
12324        1

# the list
[[2], [1], [1], [2], [1], [1], [2], [1]]

# what I want
[85, 98, 102, 715, 845, 852, 2112, 12324]
1 Answers

Sort by 'userid' then return index of top 10

new_df = df.groupby('itemid').count().sort_values(by=['userid', 'itemid'], ascending=[False, True])
print(new_df[:10].index.tolist())

we can rename the userid to user_counts, in that case we sort by user_counts

top_10 = df.groupby('itemid').count().rename(columns = {"userid": "user_counts"}).sort_values(by=['user_counts', 'itemid'], ascending=[False, True])[:10].index.tolist()
print(top_10)
Related