pandas.core.indexing.IndexingError:索引器过多

时间:2018-11-21 08:42:33

标签: python pandas

我想提取站点2的耗电量

>>> df4 = pd.read_excel(xls, 'Elec Monthly Cons')
>>> df4
     Site Unnamed: 1 2014-01-01 00:00:00 2014-02-01 00:00:00 2014-03-01 00:00:00         ...         2017-08-01 00:00:00 2017-09-01 00:00:00 2017-10-01 00:00:00 2017-11-01 00:00:00 2017-12-01 00:00:00
0    Site    Profile            JAN 2014            FEB 2014            MAR 2014         ...                    AUG 2017            SEP 2017            OCT 2017            NOV 2017            DEC 2017
1  Site 1        NHH               10344                 NaN                 NaN         ...                         NaN                 NaN                 NaN                 NaN                 NaN
2  Site 2         HH              258351              229513              239379         ...                         NaN                 NaN                 NaN                 NaN                 NaN

类型

type(df4)
<class 'pandas.core.frame.DataFrame'>

我的目标是取出数值,但我不知道如何正确设置索引。到目前为止,我所做的一切都无法奏效。

df1 = df.loc[idx[:,1:2],:]

但是

    raise IndexingError('Too many indexers')
pandas.core.indexing.IndexingError: Too many indexers

似乎我不了解索引编制。系列类型起什么作用?

df.head
<bound method NDFrame.head of Site                   Site 2
Unnamed: 1                 HH

编辑

print (df.index)
Index([             'Site',        'Unnamed: 1', 2014-01-01 00:00:00,
       2014-02-01 00:00:00, 2014-03-01 00:00:00, 2014-04-01 00:00:00,
       2014-05-01 00:00:00, 2014-06-01 00:00:00, 2014-07-01 00:00:00,

如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我认为有必要删除:,因为这意味着选择所有列,但是Series没有列。

而且似乎没有MultiIndex,所以需要:

df1 = df.iloc[1:2]

前2行是标题,因此对于MultiIndex DataFrame需要:

df4 = pd.read_excel(xls, 'Elec Monthly Cons', header=[0,1], index_col=[0,1])

然后选择使用:

idx = pd.IndexSlice
df1 = df.loc[:, idx[:,'FEB 2014':'MAR 2014']]