[英]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.