Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to groupby a column and get nlargest of another column value and return entire row using python

df = pd.DataFrame([[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3], list('AAABBBBABCBDDD'), [1.1, 1.7, 2.5, 2.6, 3.3, 3.8,4.0,4.2,4.3,4.5,4.6,4.7,4.7,4.8], ['x/y/z','x/y','x/y/z/n','x/u','x','x/u/v','x/y/z','x','x/u/v/b','-','x/y','x/y/z','x','x/u/v/w'],['1','4','3','2','4','2','5','3','6','3','5','1','2','5']]).T

df.columns = ['col1','col2','col3','col4','col5']

df

   col1 col2 col3     col4 col5
0   1.1    A  1.1    x/y/z    1
1   1.1    A  1.7      x/y    4
2   1.1    A  2.5  x/y/z/n    3
3   2.6    B  2.6      x/u    2
4   2.5    B  3.3        x    4
5   3.4    B  3.8    x/u/v    2
6   2.6    B    4    x/y/z    5
7   2.6    A  4.2        x    3
8   3.4    B  4.3  x/u/v/b    6
9   3.4    C  4.5        -    3
10  2.6    B  4.6      x/y    5
11  1.1    D  4.7    x/y/z    1
12  1.1    D  4.7        x    2
13  3.3    D  4.8  x/u/v/w    5

How to get top 2 values of col5 of col2 names and return entire row of top values. Desired output is to return as below

   col2    col1 col3    col4 col5
1   A      1.1  1.7      x/y    4
2   A      1.1  2.5  x/y/z/n    3
8   B      3.4  4.3  x/u/v/b    6
6   B      2.6    4    x/y/z    5
9   C      3.4  4.5        -    3
13  D      3.3  4.8  x/u/v/w    5
12  D      1.1  4.7        x    2

enter image description here

like image 448
manu madhavan Avatar asked Oct 23 '25 19:10

manu madhavan


1 Answers

df.groupby('col2').apply(pd.DataFrame.nlargest, n=2, columns='col5')

        col1 col2 col3     col4  col5
col2                                 
A    1   1.1    A  1.7      x/y     4
     2   1.1    A  2.5  x/y/z/n     3
B    8   3.4    B  4.3  x/u/v/b     6
     6   2.6    B    4    x/y/z     5
C    9   3.4    C  4.5        -     3
D    13  3.3    D  4.8  x/u/v/w     5
     12  1.1    D  4.7        x     2

However, you had col5 as strings. Convert them to integers

df.astype(dict(col5=int)).groupby('col2').apply(
    pd.DataFrame.nlargest, n=2, columns='col5')
like image 95
piRSquared Avatar answered Oct 26 '25 19:10

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!