尝试访问索引时,Python Pandas键错误 [英] Python Pandas Key Error When Trying to Access Index
问题描述
我在列中有以下股票数据集,在行的下方(使用彭博(Bloomberg)的Python API下载-请忽略事实,它们都是'NaN'-仅用于数据的这一部分):>
我正在尝试从索引中提取月份和年份,以便稍后进行枢轴操作:
values['month'] = values['date'].apply(lambda x: x.month)
其中值是上述DataFrame的名称.
但是这会导致错误:'KeyError'date'
运行:
values.index
看起来不错:
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)
所以我只是想知道问题出在哪里,为什么我似乎无法在此处访问实际的索引?
第一列称为index
,date
为index.name
.
您可以通过以下方式进行检查:
print (df.index.name)
因此,您需要 DatetimeIndex.month
和 DatetimeIndex.year
:>
values.index.month
对于自定义字符串格式,日期用作 strftime
:
values['name'] = values.index.strftime('%B - %Y')
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):
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.
However this gives an error: '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?
First columns is called index
and date
is index.name
.
You can check it by:
print (df.index.name)
So you need DatetimeIndex.month
and DatetimeIndex.year
:
values.index.month
EDIT:
For custom string format dates are used as strftime
:
values['name'] = values.index.strftime('%B - %Y')
这篇关于尝试访问索引时,Python Pandas键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!