Select Page

In this lesson we are going to learn how to use DataFrame.shift method to shift index by desired number of periods with an optional time freq.

When freq is not passed, shift the index without realigning the data. If freq is passed (in this case, the index must be date or datetime, or it will raise a NotImplementedError), the index will be increased using the periods and the freq.

PayPal Me: https://www.paypal.me/jiejenn/5
Venmo: @Jie-Jenn

Source Code:

``````import numpy as np
import pandas as pd

# Example 1: Shift values (by row)
df1 = pd.DataFrame({'Col1': np.arange(10, 60, 10),
'Col2': np.arange(11, 61, 10),
'Col3': np.arange(12, 62, 10)})

print(df1.shift(periods=-2).fillna(0).astype(int))

# Example 2: shift index
ind = pd.date_range('01 / 01 / 2019', periods=5, freq='12H')
df2 = pd.DataFrame({"A": [1, 2, 3, 4, 5],
"B": [10, 20, np.nan, 40, 50],
"C": [11, 22, 33, np.nan, 55],
"D": [-11, -24, -51, -36, -2],
'D1': [False] * 5,
'E': [True, False, False, True, True]},
index=ind)

print(df2.shift(freq=2, periods=3))

# Example 3: Shift values (by column)
print(df2.astype(object).shift(periods=1, axis=1).infer_objects())

``````