简体   繁体   English

如何使用二级索引列表索引 Pandas dataframe?

[英]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?我正在尝试使用列brand作为索引并从列表中添加二级索引,我该怎么做?

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分配给一个新列,然后“分解”该列并设置新索引:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 多索引熊猫数据框,如何获取特定索引列表 - Multi-index pandas dataframe, how to get list of specific indexes 如何使用熊猫等将 2 级索引转换为列索引数据框 - How to convert level 2 indexes to be columns index dataframe with pandas or etc 子集 Pandas DataFrame 二级索引和重新分配值 - Subset Pandas DataFrame Secondary Index and Reassigning values 如何用索引列表索引熊猫数据框? - how to indexing pandas dataframe with index list? 如何设置一个列表作为现有pandas dataframe的索引? - How to set a list as the index of an existing pandas dataframe? Pivot a pandas dataframe 其中值成为保留列的索引,值成为原始索引的列表 - Pivot a pandas dataframe wherein the values become indexes with retaining the columns and values become list of original index Pandas DataFrame:如何将列更改为索引,但是此新索引是当前列和索引的组合 - Pandas DataFrame: How to change a column into an index, but this new index is a combination of both the current columns and indexes 如何仅获取熊猫数据框列表的索引 0 并创建新数据框? - How to take only index 0 of a list of a pandas dataframe and create a new dataframe? pandas:返回数据帧的每个二级索引的前N行 - pandas: return first N rows of each secondary index of dataframe 基于列值的新二级索引(熊猫数据框) - New secondary index based on column value (pandas dataframe)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM