尝试访问索引时出现 Python Pandas 键错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46909102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Pandas Key Error When Trying to Access Index
提问by Curious Student
I have the following data set of stocks along the columns, dates down the rows(downloaded using Bloomberg's Python API - please ignore fact that they are all 'NaN' - this is just for this portion of the data):
我在列中有以下股票数据集,日期在行中(使用彭博的 Python API 下载 - 请忽略它们都是 'NaN' 的事实 - 这仅适用于这部分数据):
I am trying to extract the Month and Years from the Index in order to later do a pivot:
我试图从索引中提取月份和年份,以便以后进行数据透视:
values['month'] = values['date'].apply(lambda x: x.month)
Where values is the name of the above DataFrame.
其中 values 是上述 DataFrame 的名称。
However this gives an error: 'KeyError 'date'
然而,这给出了一个错误:'KeyError 'date'
Running:
跑步:
values.index
Looks fine:
看起来不错:
DatetimeIndex(['2010-01-01', '2010-01-02', '2010-01-03', '2010-01-23',
'2010-01-24', '2010-01-29', '2010-01-30', '2010-01-31',
'2010-02-13', '2010-02-14',
...
'2017-08-12', '2017-08-27', '2017-08-31', '2017-09-01',
'2017-09-03', '2017-09-09', '2017-09-24', '2017-09-29',
'2017-09-30', '2017-10-01'],
dtype='datetime64[ns]', name='date', length=593, freq=None)
So I am just wondering what is going wrong and why I don't seem able to access the actual index here?
所以我只是想知道出了什么问题,为什么我似乎无法在这里访问实际索引?
采纳答案by jezrael
First columns is called index
and date
is index.name
.
第一列被调用index
并且date
是index.name
。
You can check it by:
您可以通过以下方式检查:
print (df.index.name)
So you need DatetimeIndex.month
and DatetimeIndex.year
:
所以你需要DatetimeIndex.month
和DatetimeIndex.year
:
values.index.month
EDIT:
编辑:
For custom string format dates are used as strftime
:
对于自定义字符串格式,日期用作strftime
:
values['name'] = values.index.strftime('%B - %Y')