Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter rows with minimum values groupwise in Pandas dataframe [duplicate]

I need to select only the rows that have the minimum price:

example:

ORIGIN   | DESTINA. | PRICE
____________________________
BOG      | MAD      |  1500
BOG      | MAD      |  750
BOG      | MAD      |  1250
BOG      | MAD      |  1350
BOG      | MIA      |   450

So in this example, what I would like to get is only the third AND sixth row:

ORIGIN   | DESTINA. | PRICE
____________________________
BOG      | MAD      | 750
BOG      | MIA      | 450

Using python, how can I get this final table?

like image 780
rubio119 Avatar asked Dec 07 '25 04:12

rubio119


1 Answers

Using GroupBy + transform with min:

df = df[df['PRICE'] == df.groupby('ORIGIN')['PRICE'].transform('min')]

This will keep duplicate groupwise minima. If you don't want to keep duplicates, you can sort, then drop duplicates:

df = df.sort_values('PRICE').drop_duplicates('ORIGIN')
like image 147
jpp Avatar answered Dec 08 '25 17:12

jpp



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!