首页 > 解决方案 > 一个索引列到多索引

问题描述

我有一个标题看起来像这样的数据框:

Time Peter_Price, Peter_variable 1, Peter_variable 2, Maria_Price, Maria_variable 1, Maria_variable 3,John_price,...
2017 12           985685466           Street 1       12           4984984984          Street 2       
2018 10           985785466           Street 3       78           4984974184          Street 8 
2019 12           985685466           Street 1       12           4984984984          Street 2 
2020 12           985685466           Street 1       12           4984984984          Street 2 
2021 12           985685466           Street 1       12           4984984984          Street 2 

以后按组比较变量的最佳多指标是什么,例如哪个人的变量 3 最高或所有人的所有变量 3 的趋势

我认为我需要的是这样的东西,但我接受其他建议(这是我第一个使用多索引的方法)。

     Peter                          Maria                          John

     Price, variable 1, variable 2, Price, variable 1, variable 3, Price,...
Time

标签: pythonpandasmulti-index

解决方案


尝试:

df=df.set_index('Time')
df.columns = pd.MultiIndex.from_tuples([x.split('_') for x in df.columns])

输出:

     Peter                      Maria                      
     Price  variable1 variable2 Price   variable1 variable3
Time                                                       
2017    12  985685466  Street 1    12  4984984984  Street 2
2018    10  985785466  Street 3    78  4984974184  Street 8
2019    12  985685466  Street 1    12  4984984984  Street 2
2020    12  985685466  Street 1    12  4984984984  Street 2
2021    12  985685466  Street 1    12  4984984984  Street 2

推荐阅读