答案 0 :(得分:1)
将shift
与f-string
一起循环使用:
#python 3.6+
for i in range(1,5):
df[f'demand_{i}'] = df['demand'].shift(-i)
#python bellow 3.6
for i in range(1,5):
df['demand_{}'.format(i)] = df['demand'].shift(-i)
示例:
df = pd.DataFrame({
'demand':[4,7,8,3,5,0],
})
for i in range(1,5):
df['demand_{}'.format(i)] = df['demand'].shift(-i)
print(df)
demand demand_1 demand_2 demand_3 demand_4
0 4 7.0 8.0 3.0 5.0
1 7 8.0 3.0 5.0 0.0
2 8 3.0 5.0 0.0 NaN
3 3 5.0 0.0 NaN NaN
4 5 0.0 NaN NaN NaN
5 0 NaN NaN NaN NaN