我期待(无法看到这个已经涵盖任何地方)创建一个滑动窗口使用numpy而不是pandas.rolling (主要是为了速度)。但是,滑动窗口也必须是窗口中实例的最小和最大数目的函数,并在无法构造窗口时返回NaN。这与pandas.rolling类似,参数设置为窗口大小(最大)和min_periods。例如:
设置Min_periods =3和Max_periods = 7,参见下面指定窗口的示例:
index values intended_window
0 10 np.nan
1 11 np.nan
2 12 [10,11,12]
3 13 [10,11,12,13]
4 14 [10,11,12,13,14]
5 15 [10,11,12,13,14,15]
6 16 [10,11,12,13,14,15,16]
7 17 [11,12,13,14,15,16,17]
8 18 [12,12,14,15,16,17,18]
9 19 [13,14,15,16,17,18,19]我看到了在滑动窗口没有最大或最小要求的情况下如何构造这个滑动窗口的例子。
def rolling_window(a, window):
shp = a.shape[:-1] + (a.shape[-1] - window + 1, window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a, shape=shp, strides=strides)有人知道我如何像上面的例子那样展开它来返回窗口吗?
发布于 2021-06-15 16:57:11
请试试看以下几点。
def dataframe_striding(dataframe, window):
'''
Parameters
----------
dataframe : Input Dataframe, in this case df with columns ['index', 'values'] present.
window : Tuple denoting the window size.
Returns
-------
dataframe : Pandas Dataframe
'''
lower_end, upper_end = window
if lower_end > upper_end:
raise ValueError('Check window size!')
results = []
for i in range(dataframe.shape[0]):
l = [k for k in dataframe['values'][:i+1]]
if len(l) < lower_end: # checks for minimum window length
l = np.nan
results.append(l)
elif lower_end <= len(l) <= upper_end: # checks for required window length
results.append(l)
else: # checks for maximum window length
l = l[-upper_end:]
results.append(l)
dataframe['rolling_output'] = results # appends output to input dataframe
return dataframe
# run above function #
final_df = dataframe_striding(df, window = (4,6))发布于 2021-06-15 12:01:24
values = np.linspace(1, 10, num=10)
window_column = []
for i in range(len(values)):
if i - 7 < 0:
t = 0
else:
t = i - 7
window = values[t:i]
if len(window) < 3:
window_column.append(np.nan)
else:
window_column.append(window)https://stackoverflow.com/questions/67985651
复制相似问题