Examples of how to shift values in a dataframe column with pandas:
Create a dataframe with pandas
Let's first create a dataframe with pandas:
import pandas as pdimport numpy as npdata = np.arange(1,31)data = data.reshape(10,3)df = pd.DataFrame(data=data,columns=['a','b','c'])print(df)
gives then
a b c0 1 2 31 4 5 62 7 8 93 10 11 124 13 14 155 16 17 186 19 20 217 22 23 248 25 26 279 28 29 30
Shift dataframe values for a given column
Shifting rows down or up
To shift, for example, 3 rows down for the column c, a solution is to use pandas.DataFrame.shift. Parameter "periods" defined
the number of rows to shift:
df = df['c'].shift(periods=3)print(df)
gives
0 NaN1 NaN2 NaN3 3.04 6.05 9.06 12.07 15.08 18.09 21.0Name: c, dtype: float64
To shift 3 rows up for the column c
df = pd.DataFrame(data=data,columns=['a','b','c'])df = df['c'].shift(periods=-3)print(df)
gives
0 12.01 15.02 18.03 21.04 24.05 27.06 30.07 NaN8 NaN9 NaNName: c, dtype: float64
Another example shifting only 1 row:
df = pd.DataFrame(data=data,columns=['a','b','c'])df = df['c'].shift(periods=1)print(df)
gives
0 NaN1 3.02 6.03 9.04 12.05 15.06 18.07 21.08 24.09 27.0Name: c, dtype: float64
Define fill_value
By default fill_value is NaN but it is possible to define another value using the parameter fill_value:
df = pd.DataFrame(data=data,columns=['a','b','c'])df = df['c'].shift(periods=3, fill_value=-99999)print(df)
gives
0 -999991 -999992 -999993 34 65 96 127 158 189 21Name: c, dtype: int64
Create new columns with nearest neighbors values
Another example let's create new columns with nearest neighbors values
df = pd.DataFrame(data=data,columns=['a','b','c'])df["n+1"] = df['c'].shift(periods=1, fill_value=-99999)df["n+2"] = df['c'].shift(periods=2, fill_value=-99999)df["n-1"] = df['c'].shift(periods=-1, fill_value=-99999)df["n-2"] = df['c'].shift(periods=-2, fill_value=-99999)print(df)
gives
a b c n+1 n+2 n-1 n-20 1 2 3 -99999 -99999 6 91 4 5 6 3 -99999 9 122 7 8 9 6 3 12 153 10 11 12 9 6 15 184 13 14 15 12 9 18 215 16 17 18 15 12 21 246 19 20 21 18 15 24 277 22 23 24 21 18 27 308 25 26 27 24 21 30 -999999 28 29 30 27 24 -99999 -99999
