I have some initial data that looks like this:
code type value
1111 Golf Acceptable
1111 Golf Undesirable
1111 Basketball Acceptable
1111 Basketball Undesirable
1111 Basketball Undesirable
and I'm trying to group it on the code
and type
columns to get the row with the most occurrences. In the case of a tie, I want to select the row with the value Undesirable
. So the example above would become this:
code type value
1111 Golf Undesirable
1111 Basketball Undesirable
Currently I'm doing it this way:
df = pd.DataFrame(df.groupby(['code', 'type', 'value']).size().reset_index(name='count'))
df = df.sort_values(['type', 'count'])
df = pd.DataFrame(df.groupby(['code', 'type']).last().reset_index())
I've done some testing of this and it seems to do what I want, but I don't really like trusting the .last()
call, and hoping in the case of a tie that Undesirable
was sorted last. Is there a better way to group this to ensure I always get the higher count, or in the cases of a tie select the Undesirable
value?
Performance isn't too much of an issue as I'm only working with around 50k rows or so.