简体   繁体   中英

How to index a Pandas dataframe with a list of secondary indexes?

I'm trying to use the column brand as an index and add a secondary index from a list, how can I do that?

import pandas as pd   
cars = {'brand': ['Honda Civic','Toyota Corolla'], 'price': [22000,25000]}  
df = pd.DataFrame(cars, columns = ['brand', 'price'])
print (df)

            brand  price
0     Honda Civic  22000
1  Toyota Corolla  25000

Pattern of the secondary index is taken from a list.

model = [['A', 'B'], ['C']]

Desired result:

                       price
         brand  model  
   Honda Civic      A  22000
                    B  22000
Toyota Corolla      C  25000

You can assign your list model to a new column, then "explode" this column and set new index:

model = [['A', 'B'], ['C']]
df = df.assign(model=model).explode('model').set_index(['brand', 'model'])
print(df)

Prints:

                      price
brand          model       
Honda Civic    A      22000
               B      22000
Toyota Corolla C      25000

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM