熊猫:如何读取定义多列的excel文件为多索引?

时间:2016-06-27 04:02:03

标签: python excel date pandas dataframe

我有一个数据框,每一行都包含一个办公室位置对象,其中包含多个属性,如Global RegionPrimary Function,以及几个能耗数据作为数值。所有列的名称如下所示:

['Global Region',  
'Primary Function',  
'Subsidiaries',  
'T&D Loss Rate Category',  
'Type',  
'Ref',  
'Acquisition date',  
'Disposal date',  
'Corporate Admin Approver',  
'Data Providers',  
'Initiative administrator',  
'Initiative approver',  
'Initiative user',  
'Invoice owner',  
'Apr to Jun 2012',  
'Jul to Sep 2012',  
'Oct to Dec 2012',  
'Jan to Mar 2013',  
'Apr to Jun 2013',  
'Jul to Sep 2013',  
'Oct to Dec 2013',  
'Jan to Mar 2014',  
'Apr to Jun 2014',  
'Jul to Sep 2014',  
'Oct to Dec 2014',  
'Jan to Mar 2015',  
'Apr to Jun 2015',  
'Jul to Sep 2015',  
'Oct to Dec 2015',  
'Jan to Mar 2016']  

如何根据不同属性对不同位置进行排序和查看数据,例如基于primary functionglobal region。我可以看到primary functio n是R& D的所有位置的平均能量消耗或等级能量强度。

我想到了多指数,但我不知道该怎么做。我试过这个:

test = xls.parse('Sheet1',index_col=['Lenovo Global Region','Primary Function', 'Subsidiaries', 'Type','Acquisition date','Disposal date','Country'])

它没有用,错误说我只能使用数字而不是字符串,所以我尝试了这个:

test = xls.parse('Sheet1',index_col=0,1,3,4,5,7,9,10)

仍然没有工作。有人有好的建议吗?

1 个答案:

答案 0 :(得分:1)

您可以将read_excel与参数index_col一起使用,其中包含list个必要列的位置:

样品:

df = pd.read_excel('test.xlsx', sheetname='Sheet1', index_col=[0,1,3])
print (df)
                                                      Subsidiaries Type  Ref
Global Region Primary Function T&D Loss Rate Category                       
1             1                c                                 a    s   10
2             2                c                                 b    d   20
3             3                d                                 c    d   30

excel

Reading a multiindex

因此,如果添加[],它可以起作用:

test = xls.parse('Sheet1',index_col=[0,1,3,4,5,7,9,10])