pandas: create n new columns to contain last n values (rolling)

Viewed 28

consider this sample data:

import pandas as pd
import numpy as np
thisDict = {0: '20141216',
 1: '20150115',
 2: '20150212',
 3: '20150316',
 4: '20150415',
 5: '20150514',
 6: '20150615',
 7: '20150716',
 8: '20150814',
 9: '20150915'}
pd.DataFrame.from_dict(thisDict, orient = 'index')

I want basically to turn this into a new dataframe with n columns, where for each row we have the last n values. Consider the data above, for n = 3, it would be:

    pd.DataFrame.from_dict({0: [np.nan,np.nan ,np.nan] ,
     1: ['20141216',np.nan,np.nan],
     2: ['20141216','20150115', np.nan],
     3: ['20150316','20150115','20150212'],
...
    },orient = 'index')
1 Answers

For one, you can do a concat:

n=3
pd.concat([df.shift(i) for i in range(n)], axis=1)

Output:

          0         0         0
0  20141216       NaN       NaN
1  20150115  20141216       NaN
2  20150212  20150115  20141216
3  20150316  20150212  20150115
4  20150415  20150316  20150212
5  20150514  20150415  20150316
6  20150615  20150514  20150415
7  20150716  20150615  20150514
8  20150814  20150716  20150615
9  20150915  20150814  20150716
Related