Chris L
Chris L

Reputation: 329

How to change a specific date value in an index?

I am trying to change the last index value in a dateframe to another date.

from datetime import datetime, timedelta
import pandas as pd
import numpy as np

date_1 = datetime(2021,5,31,0,0)
date_2 = datetime(2021,6,30,0,0)
df=pd.DataFrame(index={date_1,date_2},data = {1,2},columns={'X'})

I also have a variable for the date I want, which is of type datetime

last_dt = datetime(2021, 6, 24, 0, 0)

When I try and join the two I get an error message "Index does not support mutable operations"

df.index[-1]=last_dt

While the index is also of the type datetime, the last value (df.index[-1]) is of type timestamp.

type(df.index[-1])
pandas._libs.tslibs.timestamps.Timestamp

I am guessing this mismatch is what is causing the error but not sure how to solve it.

Upvotes: 2

Views: 552

Answers (2)

rhug123
rhug123

Reputation: 8768

Here is an alternative way:

df.set_axis((df.index[:-1].union([last_dt],sort=False)),axis=0)

Upvotes: 0

Mustafa Aydın
Mustafa Aydın

Reputation: 18306

pd.Index objects don't support item assignment directly, so one way is to construct the new index manually and assign it back:

# we put the values till last one as is and add `last_dt` at last
df.index = [*df.index[:-1], last_dt]

or you can manipulate the underlying array:

df.index.array[-1] = last_dt

Upvotes: 2

Related Questions