apply a filter to a dataframe based on conditions

Let’s use pd.cut to map the Rankings to numbers of rows to extract, then compare those to the relative row numbers with groupby().cumcount() :

thresh = pd.cut(df['Ranking'], bins=[0,4,12,16,20], 
                labels=[4,3,2,1]).astype(int)

df.loc[df.sort_values(['Points'])
         .groupby('Ranking').cumcount().lt( thresh), 'Team']

Output:

0     A
1     B
2     C
3     D
4     E
5     F
7     H
11    L
12    M
15    P
16    Q
17    R
19    T
20    U
21    V
22    X
23    Y
24    Z
Name: Team, dtype: object

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top