0

Assuming I have the following test DataFrame df:

Car      Sold      make       profit 

Honda     100      Accord      10
Honda      20      Fit          5
Toyota    300      Corolla     20
Hyundai   150      Elantra     20
BMW        20      Z-class    100 
Toyota     45      Lexus        7
BMW        50      X-class     30
JEEP      150      cherokee     2
Honda      20      CRV          5
Toyota     30      Yaris        3

I need a summary statistic table for number of cars sold, by type of car.

I can do that this way:

df.groupby('Car')['Sold'].describe()

this gives me something like the following:

Car      count      mean       std     min    25th   50th   75th    max  

BMW        2       
Honda      3        
Hyundai    1  
JEEP       1   
Toyota     3      

The 'Car' column values are listed in the summary statistic table in alphabetically ascending order. I am looking for a way to sort it in my own pre-specified way. I want the summary statistic table to be listed as "Toyota, Hyundai, JEEP, BMW, Honda"

smci
  • 32,567
  • 20
  • 113
  • 146
JodeCharger100
  • 903
  • 1
  • 12
  • 25
  • Does this answer your question? [pandas groupby sort descending order](https://stackoverflow.com/questions/27018622/pandas-groupby-sort-descending-order) – Joe May 24 '20 at 02:42
  • Are you always going to have a complete specific new order? As you can always add a `.reindex` and give it a list of the new desired order, but if you add ones that don't exist you'll get all columns as NaNs and if you miss one off by accident - it'll just vanish but then that may well be desirable behaviour... – Jon Clements May 24 '20 at 02:45
  • 1
    Don't title things "Python function" if they're specific to pandas. – smci Dec 05 '21 at 03:56

1 Answers1

0
df.groupby('Car')['Sold'].describe().loc[["Toyota", "Hyundai", "JEEP", "BMW", "Honda"]]

helps me put it in order, but I am not able to do it for multi-level indexing. For instance, if I want the summary statistics table by 'Car', and further by the make, .loc does not give me the desired solution.

JodeCharger100
  • 903
  • 1
  • 12
  • 25