我有以下数据集:
data = {
'date': ['1/1/2019', '1/2/2019', '1/3/2019', '1/4/2019', '1/1/2019', '1/2/2019', '1/3/2019', '1/4/2019'],
'account_id': [1, 1, 1, 1, 2, 2, 2, 2],
'value_1': [1, 2, 3, 4, 5, 6, 7, 8],
'value_2': [1, 3, 6, 9, 10, 12, 14, 16]
}
df = pd.DataFrame(data,index = data['date']).drop('date', 1)
df我需要的是将值1和值2向前推30天。
我偶然发现了Extrapolate Pandas DataFrame。如果date列中没有重复的条目,它会工作得很好。
我想过使用这种东西,但我不知道如何将v添加到函数中:
def extrapolation(df):
extend = 1
y = pd.DataFrame(
data=df,
index=pd.date_range(
start=df.index[0],
periods=len(df.index) + extend
)
)
#then, the extrapolation piece
df_out=df.head(0).copy()
for k,v in df.groupby('account_id'):
df_out=pd.concat([df_out,extrapolation(df)])发布于 2019-06-12 02:21:18
您可以修改链接答案,如下所示:
def extrapolate(df):
new_max = df.index.max() + pd.to_timedelta('30D')
dates = pd.date_range(df.index.min(), new_max, freq='D')
ret_df = df.reindex(dates)
x = np.arange(len(df))
# new x values
new_x = pd.Series(np.arange(len(ret_df)), index=dates)
for col in df.columns:
fit = np.polyfit(x, df[col], 1)
# tranform and fill
ret_df[col].fillna(fit[0]*new_x + fit[1], inplace=True)
return ret_df然后应用:
ext_cols = ['value_1', 'value_2']
df.groupby('account_id')[ext_cols].apply(extrapolate)您还可以为每列指定多项式阶数:
poly_orders = [1,2]
ext_cols = ['value_1', 'value_2']
def extrapolate(df):
new_max = df.index.max() + pd.to_timedelta('30D')
dates = pd.date_range(df.index.min(), new_max, freq='D')
ret_df = df.reindex(dates)
x = np.arange(len(df))
# new x values
new_x = pd.Series(np.arange(len(ret_df)), index=dates)
for col, o in zip(ext_cols, poly_orders):
fit = np.polyfit(x, df[col], o)
print(fit)
# tranform and fill
new_vals = pd.Series(0, index=dates)
for i in range(1,o+1):
new_vals = new_x**i * fit[o-i]
ret_df[col].fillna(new_vals, inplace=True)
return ret_df并使用sklearn.linear_model.LinearRegression代替numpy.polyfit,以便更好地处理输入/输出。
https://stackoverflow.com/questions/56548280
复制相似问题