Pandas groupby two columns and get max value
I have grouped data with multiindex
Model VehicleType VehicleType
100 sedan 278
wagon 109
coupe 2
convertible 1
145 small 19
... ...
zafira sedan 22
small 11
suv 7
convertible 1
coupe 1
I need to get max value of count (right column) with corresponding model and VehicleType, like this:
Model VehicleType VehicleType
100 sedan 278
145 small 19
... ...
zafira sedan 22
Thanks for solutions!
Use DataFrameGroupBy.idxmax
for indices by maximum value and then select by DataFrame.loc
:
df = df.loc[df.groupby(level=0)['VehicleType'].idxmax()]
print (df)
VehicleType
Model VehicleType
100 sedan 278
145 small 19
zafira sedan 22
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.