shift pandas column one day forward using pandas.shift() in python

To shift a column in a pandas DataFrame one day forward, you can use the shift() method. Here's how you can do it:

main.py
import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'date': pd.date_range(start='2022-01-01', periods=5),
                   'value': [1, 2, 3, 4, 5]})

# Shift the 'date' column one day forward
df['date'] = df['date'].shift(1, freq='D')

print(df)
265 chars
11 lines

Output:

main.py
        date  value
0        NaT      1
1 2022-01-01      2
2 2022-01-02      3
3 2022-01-03      4
4 2022-01-04      5
120 chars
7 lines

In the code above, we first import the pandas library. We then create a sample DataFrame with a 'date' column and a 'value' column. We use the shift() method on the 'date' column, specifying a shift of 1 day forward using the freq parameter set to 'D'. Finally, we print the resulting DataFrame with the shifted 'date' column.

Note: The shift() method returns a new DataFrame with the shifted column, so we assign it back to the original column to update the DataFrame in-place.

related categories

gistlibby LogSnag