How do I shift a Datetime index by a day inside a Multi-index dataframe?

Viewed 24
                     columnA     columnB
symbol  timestamp                         
AAPL    2022-08-17
AAPL    2022-08-17

TSLA    2022-08-17
TSLA    2022-08-17

I am trying to shift all timestamps by one day.

I have this:

new_dates = df.index.get_level_values(1) +  pd.Timedelta(days=1)

How do I apply it to the dataframe?

1 Answers

With the dataframe you provided as example:

import pandas as pd

df = pd.DataFrame(
    {
        "stock": ["AAPL", "AAPL", "TSLA", "TSLA"],
        "date": ["2022-08-17", "2022-08-17", "2022-08-17", "2022-08-17"],
        "columnA": ["", "", "", ""],
        "columnB": ["", "", "", ""],
    }
)
df["date"] = pd.to_datetime(df["date"])
df = df.set_index(["stock", "date"])

Here is one way to do it:

new_dates = df.index.get_level_values(1) + pd.Timedelta(days=1)

df = df.reset_index().assign(date=new_dates).set_index(["stock", "date"])
print(df)
# Output
                 columnA columnB
stock date
AAPL  2022-08-18
      2022-08-18
TSLA  2022-08-18
      2022-08-18
Related