I have a dataframe of ids, states, places, types and populations:
| id | state | place | type | population |
|---|---|---|---|---|
| A | ontario | toronto | Place | 5429524.0 |
| A | ontario | ottawa | Capital | 989567.0 |
| B | saskatchewan | saskatoon | Place | 246376.0 |
| B | saskatchewan | regina | Place | 215106.0 |
| B | saskatchewan | moose jaw | Place | 33890.0 |
I groupby to get all states with the same ID:
grouped_df = locations_df.groupby(["id", "state"])
I then need to either get the row that has ['type']== 'Capital' OR if that doesn't exist in that group, then choose the row with the highest population. e.g.
| id | state | place | type | population |
|---|---|---|---|---|
| A | ontario | ottawa | Capital | 989567.0 |
| B | saskatchewan | saskatoon | Place | 246376.0 |
I can get these individually using:
locations_df.groupby(["id", "state"]).population.idxmax()
locations_df.groupby(["id", "state"]).filter(lambda x: (x['type']== 'Capital').any())
Is there a way to combine this into one call?