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?
How to Fix the KeyError? We can simply fix the error by correcting the spelling of the key. If we are not sure about the spelling we can simply print the list of all column names and crosscheck.
Use DataFrame.reset_index() function reset_index() to reset the index of the updated DataFrame. By default, it adds the current row index as a new column called 'index' in DataFrame, and it will create a new row index as a range of numbers starting at 0.
In order to access the series element refers to the index number. Use the index operator [ ] to access an element in a series. The index must be an integer. In order to access multiple elements from a series, we use Slice operation.
IndexError is an exception in python that occurs when we try to access an element from a list or tuple from an index that is not present in the list. For example, we have a list of 10 elements, the index is in the range 0 to 9.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With