how to shift a column backwards in python

You can shift a pandas dataframe column backwards using the shift() method of pandas.

Here is how to shift a column named col_name in dataframe df backwards by n positions:

main.py
df[col_name] = df[col_name].shift(periods=n) 
46 chars
2 lines

Where periods is the number of positions to shift backwards.

Here's an example:

main.py
import pandas as pd

df = pd.DataFrame({'A':[1,2,3,4], 'B':[5,6,7,8]})

df['B'] = df['B'].shift(periods=1) 

print(df)
119 chars
8 lines

This outputs:

main.py
   A    B
0  1  NaN
1  2  5.0
2  3  6.0
3  4  7.0
50 chars
6 lines

As you can see, the B column has been shifted backwards by one position.

related categories

gistlibby LogSnag