Andy Jensen
Andy Jensen

Reputation: 93

Python - Create Column based on max date in Multi Index DF

I have a Multi Index dataframe and the first index is a datetime index. I want to find the maximum date from the date index and then create a new column with that value.

I'm able to find the max date by using:

    df.index.max()

    (Timestamp('2021-01-01 00:00:00'), 'c')

When I try and create a new column with this date, I get an error that says, "Length of values does not match length of index":

 df['maxdate'] = df.index.max()

This is how the table currently is:

This is how it currently is

This is how I want the table to look:

enter image description here

Can someone please help me?

Upvotes: 0

Views: 934

Answers (1)

osint_alex
osint_alex

Reputation: 1022

Only a small change needed!

Change this

df['maxdate'] = df.index.max()

to:

df['maxdate'] = df.index.max()[0]

Calling df.index.max() returns a tuple with two objects, the date and company. Since you want to use just the date, you have to access that since it's the first item.

Upvotes: 1

Related Questions