【问题标题】:Pandas: How to read an excel file defining several columns to be multi indexes?Pandas:如何读取定义多个列作为多索引的 excel 文件?
【发布时间】:2016-10-28 23:34:16
【问题描述】:

我有一个数据框,其中每一行都包含一个办公室位置对象,该对象具有多个属性,例如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 function 为研发的所有地点的平均能源消耗或能源强度等级。

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

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)

还是不行。有人有好的建议吗?

【问题讨论】:

    标签: python excel date pandas dataframe


    【解决方案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
    

    Reading a multiindex.

    所以如果添加[]它可以工作:

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

    【讨论】:

    • 我做了同样的事情,但它给了我,ValueError: Expected 63 fields in line 2, saw 56
    • 我的excel有55列
    • 第 2 行中的数据看起来像坏数据。
    • 我只使用index_col=[0]时有效,使用多列时无效。
    • 可能第一列没有名字,所以pandas认为是index
    猜你喜欢
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 2020-11-12
    • 2021-09-28
    • 1970-01-01
    • 2018-09-08
    • 2014-07-31
    • 2020-01-29
    相关资源
    最近更新 更多