How to apply consecutive filters on same dataframe?

Viewed 18

I have this dataframe:

car_model store_location year_buying car_color
Ferrari   LA             2010        Red
Ferrari   LA             2010        Pink
Ferrari   Paris          2010        Yellow
Mercedes  LA             2012        Red
Mercedes  Roma           2022        Grey

I am trying to apply multiple filters on this dataframe:

  1. For each car_model, how many possible store_location do I have and count each of them (example: Ferrari 2 store location and 2 for LA and 1 for Paris).

  2. With the answer of 1), for each type store location (example: for Ferrari store locations, LA and Paris) how many possible year_buying do I have and count them.

  3. With the answer of 2), for year_buying how many possible car_color do I have and count them

For 1) I did this:

df.groupby(['car_model','store_location'])['store_location'].count()

I have the store location and number of store location by car. But it is a Pandas Series and I don't know how to apply next filters. I would like to keep results of 1), 2) and 3).

How can I do this ?

1 Answers

It is not possible extract information about another column from s1, because are removed. You can processing original DataFrame:

s1 = df.groupby(['car_model','store_location']).size()
s2 = df.groupby(['car_model','store_location','year_buying']).size()
s3 = df.groupby(['car_model','store_location','year_buying','car_color']).size()
Related