دنبال کننده ها

۱۳۹۶ بهمن ۱۲, پنجشنبه

pandas - Python: filter panadas dataframe to keep specified number of rows based on a column

[ad_1]



I have a pandas dataframe which looks like:



id name grade
1 A 10
1 A 12
1 A 15
2 B 20
3 C 19
3 C 16
3 C 11


And need to make it look like:



id name grade
1 A 12
1 A 15
2 B 20
3 C 19
3 C 16


In this case I need to keep top 2 rows for each id with highest grades. I know I could use iloc and iterate through the dataframe but am wondering if there is a more pythonic way of doing this. Is this possible at all? Thanks in advance



Btw, feel free to edit the question and give it a better title if you have anything in mind.




[ad_2]

لینک منبع