Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas Key Error When Trying to Access Index

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):

enter image description here

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?

like image 870
Curious Student Avatar asked Oct 24 '17 11:10

Curious Student


People also ask

How do I fix Pandas key error?

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.

How do I fix Pandas index?

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.

How do I access the Pandas Series index?

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.

What is index error in Pandas?

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.


1 Answers

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')
like image 176
jezrael Avatar answered Oct 10 '22 22:10

jezrael