8

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?

1 Answer 1

6

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')
Sign up to request clarification or add additional context in comments.

10 Comments

In the final code snippet for values.index - doesn't it show that the index name='date' - or have I misunderstood something here?
It is print (df.index.name)
Btw, what is desired output after pivoting? Because I see MultiIndex in columns.
You write that "First columns is called index", but if I try calling df['index'] it fails, while if I provided any other column's name, it would have returned values for that column. So, how can I use the same syntax for the Index? What do I provide it df[???] to get values of the index. Thank you
@Confounded - df.index ;)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.