Sorting across columns


This is in relation to the Exploring eBay Car Sales Data guided project.

I am attempting to sort vehicles by price, and display the top 3 entries for each brand of car. My code correctly displays the most expensive cars by brand, but I would like the top 3 entries for each brand.

Any suggestions would be much appreciated! Thank you!

My Code:


The above code displays the following:

        price           brand  registration_year
36818  350000         porsche               2016
14715  345000  sonstige_autos               2012
47337  259000             bmw               2001

Though I would like it to display the top 3 most expensive cars for porsche, for sonstige, bmw, etc…

I hope will be useful for you.

def combi_marca_modelo(brand):
    boolean_brand = auto_clean['brand'] == brand 
    return auto_clean.loc[boolean_brand,'model'].value_counts()[:5] # top 5


a4        1125
a3         788
a6         771
andere     212
tt         144
Name: model, dtype: int64



1 Like

Hi @Edelberth,

Thanks for the suggestion!

I borrowed your idea and came up with the following, which would work with an iterative loop.

def sort_top_brands(brand):
    bool = data['brand'] == brand
    return data.loc[bool,['price','registration_year']].sort_values(by='price',ascending=False).head(3)
        price  registration_year
36818  350000               2016
34723  299000               1977
35923  295000               2015
for i in data['brand'].unique():
1 Like

I’m glad to see that it has inspired you.

Best regards!