0

I am trying to do something like an SQL window function in Python 3.6. I have created the following code which I found here, but I'm getting the following error:

"ValueError: cannot reindex from a duplicate axis"

df = pd.DataFrame({'id' : ['daeb21718d5a','daeb21718d5a','daeb21718d5a'],
           'product_id' : [123,456,789],
           'probability' : [0.076838,0.053384, 0.843900 ]})

df['rank'] = df.sort_values(['probability'], ascending=False) \
               .groupby(['id']) \
               .cumcount() + 1

Weirdly if I add .reset_index(drop=True) before grouping, the error is fixed.

Mewtwo
  • 1,091
  • 16
  • 36

1 Answers1

1

If I understand you correctly, you are trying to rank probability descending based on each group of id.

You were almost there, the following will solve your problem:

df['rank'] = df.sort_values(['probability'], ascending=False) \
             .groupby(['id'])['probability'] \
             .cumcount() + 1

print(df)
             id  product_id  probability  rank
0  daeb21718d5a         123     0.076838     2
1  daeb21718d5a         456     0.053384     3
2  daeb21718d5a         789     0.843900     1

Or we can use pandas .rank method for this:

df['rank'] = df.groupby('id')['probability'].rank(ascending=False)

print(df)
             id  product_id  probability  rank
0  daeb21718d5a         123     0.076838   2.0
1  daeb21718d5a         456     0.053384   3.0
2  daeb21718d5a         789     0.843900   1.0
Erfan
  • 36,997
  • 6
  • 53
  • 68