Pandas scoring n.lowest value of each date into a new column

Viewed 57

I have been spending too long for this what should be easy but..

I have dataset:

    date    score1    score2
0   1.8.2020      10      11
1   1.8.2020      15      10
2   1.8.2020      16       7
3   2.8.2020       8       7
4   2.8.2020       2       9
5   2.8.2020       6       8
6   3.8.2020       8       3
7   3.8.2020       5       4
8   4.8.2020       1       5
9   4.8.2020       1       3
10  4.8.2020       0       5

For each day: I want to find the 2nd lowest score of column "score1" values for that date and create new column called result1 with value 1 if the value for the day in that row was 2nd lowest and 0 if not.(If score would be same for multiple days, could give 1 for both)

For example 1.8.2020 the second lowest value is at row 1, value 15 and this row should be given 1 point in "result1" column.

The result should look like this:

    date       score1  score2  result1
0   1.8.2020      10      11        0
1   1.8.2020      15      10        1
2   1.8.2020      16       7        0
3   2.8.2020       8       7        0
4   2.8.2020       2       9        0
5   2.8.2020       6       8        1
6   3.8.2020       8       3        1
7   3.8.2020       5       4        0
8   4.8.2020       1       5        1
9   4.8.2020       1       3        1
10  4.8.2020       0       5        0

Same logic could also be applied to column score2 creating another column result2.

1 Answers

This is an application of rank:

rank = df.groupby('date')['score1'].rank(method='dense')-1
df['result1'] = rank.eq(1).astype(int)

Output:

        date  score1  score2  result1
0   1.8.2020      10      11        0
1   1.8.2020      15      10        1
2   1.8.2020      16       7        0
3   2.8.2020       8       7        0
4   2.8.2020       2       9        0
5   2.8.2020       6       8        1
6   3.8.2020       8       3        1
7   3.8.2020       5       4        0
8   4.8.2020       1       5        1
9   4.8.2020       1       3        1
10  4.8.2020       0       5        0
Related