主要问题是将行附加到数据帧是一个非常低效的过程(即每次迭代创建一个新的数据帧系列并将其附加到原始数据帧将非常昂贵)。
可能最好的方法是从数据帧创建一个数组,在那里进行滚动计算,然后将结果转换为新的数据帧。
import pandas as pd
import numpy as np
# create dataframe with the first month removed to show the solution is generalizable
df = pd.DataFrame({'month':[2,3,4,5,6],'val1':[3,5,7,2,2],'val2':[4,1,4,6,2],'val3':[7,2,3,4,2]})
df
month val1 val2 val3
0 2 3 4 7
1 3 5 1 2
2 4 7 4 3
3 5 2 6 4
4 6 2 2 2
# extract values of the dataframe as numpy and perform rolling operations
# separate out months from other columns
array_values = df.drop(columns = 'month').values
# loop from most recent month to month 12
for month in range(df.month.iloc[-1],12):
array_values = np.append(array_values, np.apply_along_axis(np.mean, 0,array_values[-2:]).reshape(1,3), axis = 0)
array_months = np.append(df.month.values, np.arange(df.month.values[-1]+1,13,1))
array_months = array_months.reshape(len(array_months),1)
array_values = np.append(array_months, array_values, axis = 1)
new_df = pd.DataFrame(data = array_values, columns = df.columns)
new_df.month = new_df.month.astype('int')
输出:
new_df
month val1 val2 val3
0 2 3.0 4.0000 7.00000
1 3 5.0 1.0000 2.00000
2 4 7.0 4.0000 3.00000
3 5 2.0 6.0000 4.00000
4 6 2.0 2.0000 2.00000
5 7 2.0 4.0000 3.00000
6 8 2.0 3.0000 2.50000
7 9 2.0 3.5000 2.75000
8 10 2.0 3.2500 2.62500
9 11 2.0 3.3750 2.68750
10 12 2.0 3.3125 2.65625