Skip to content Skip to sidebar Skip to footer

Sqlish Window Function In Python

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: cann

Solution 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

Post a Comment for "Sqlish Window Function In Python"