Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

Convert this User-Category Score into User-Top3-Category score DataFrame with User and there 3 max Categories name in Python Pandas Dataframe

Input DataFrame

user_id  cat_1  cat_2   cat_3   cat_4   cat_5   cat_6

1        0.10   0.2     0.20    0.12    0.7     0.6 

2        0.6    0.20    0.12    0.15    0.13    0.11    

3        0.11   0.10    0.8     0.12    0.3     0.7

4        0.2    0.11    0.12    0.6     0.9     0.21

5        0.9    0.8     0.5     0.1     0.0     0.11    

Desired Output DataFrame

user_id     top_3_categories

1           [cat_3, cat_4, cat_1]

2           [cat_2, cat_4, cat_3]

3           [cat_4, cat_1, cat_2]

4           [cat_6, cat_3, cat_2]

5           [cat_6, cat_1, cat_2]   

1 Answer

0 votes
by (41.4k points)

Using  numpy.argsort :

df = df.set_index('user_id')

arr = df.columns.values[np.argsort(-df.values)[:, -3:]].tolist()

df1 = pd.DataFrame({'user_id': df.index, 'top_3_categories':arr})

print (df1)

   user_id       top_3_categories

0        1  [cat_3, cat_4, cat_1]

1        2  [cat_5, cat_3, cat_6]

2        3  [cat_4, cat_1, cat_2]

3        4  [cat_1, cat_3, cat_2]

4        5  [cat_6, cat_4, cat_5]

Related questions

Browse Categories

...