考虑这个示例数据:
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')
我基本上想将其转换为一个具有 n 列的新数据框,其中每行都有最后 n 个值。 考虑上面的数据,对于 n = 3,它将是:
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')
最佳答案
首先,您可以进行连接:
n=3
pd.concat([df.shift(i) for i in range(n)], axis=1)
输出:
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
关于python - pandas:创建 n 个新列来包含最后 n 个值(滚动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64878086/