如何在没有 Pandas STD 或 Mean 函数的情况下计算滚动 STD?
How Do I Calculate Rolling STD Without Pandas STD or Mean functions?
我想将 Rolling STD 合并到我的 Rolling Mean 函数中。由于它产生的 Nan 值,我不能使用 Pandas std。我不确定如何计算平方和。有什么建议么?我需要列表理解吗?
def rolling_mean_std(x, wd_size=3):
rolling_mean, rolling_std = None, None
i = 0
rolling_mean = []
rolling_std = []
while i < len(x) - wd_size + 1:
if i<=wd_size:
this_window = x[0 : 1 + i]
window_average = sum(this_window) / (i+1)
##Edit to include std calculation
window_std = sum((x - window_average) ** 2 for x in this_window)/(i+1)
squirt=math.sqrt(window_std)
rolling_mean.append(window_average)
rolling_std.append(math.sqrt(squirt))
i += 1
else:
this_window = ser[i : i + wd_size]
window_average = sum(this_window) / wd_size
##Edit to include std calculation
window_std = sum((x - window_average) ** 2 for x in this_window)/wd_size
squirt=math.sqrt(window_std)
rolling_mean.append(window_average)
rolling_std.append(math.sqrt(squirt))
i += 1
return np.array(rolling_mean) #np.array(rolling_std)
alist = [2,4,5,7,9,10,21,89,43,90,13,100,1,45]
x = pd.Series(alist)
rolling_mean_std(x, wd_size=3)
您可以尝试使用 Pandas rolling
函数并计算每个滚动 window 的标准差,并将每个标准差追加到列表中以获得滚动标准差。滚动方式相同。
例如:
wd_size = 3
alist = [2,4,5,7,9,10,21,89,43,90,13,100,1,45]
x = pd.Series(alist)
rolling_mean = []
rolling_std = []
for i in x.rolling(window = wd_size):
rolling_mean.append(np.mean(i))
rolling_std.append(np.std(i))
我想将 Rolling STD 合并到我的 Rolling Mean 函数中。由于它产生的 Nan 值,我不能使用 Pandas std。我不确定如何计算平方和。有什么建议么?我需要列表理解吗?
def rolling_mean_std(x, wd_size=3):
rolling_mean, rolling_std = None, None
i = 0
rolling_mean = []
rolling_std = []
while i < len(x) - wd_size + 1:
if i<=wd_size:
this_window = x[0 : 1 + i]
window_average = sum(this_window) / (i+1)
##Edit to include std calculation
window_std = sum((x - window_average) ** 2 for x in this_window)/(i+1)
squirt=math.sqrt(window_std)
rolling_mean.append(window_average)
rolling_std.append(math.sqrt(squirt))
i += 1
else:
this_window = ser[i : i + wd_size]
window_average = sum(this_window) / wd_size
##Edit to include std calculation
window_std = sum((x - window_average) ** 2 for x in this_window)/wd_size
squirt=math.sqrt(window_std)
rolling_mean.append(window_average)
rolling_std.append(math.sqrt(squirt))
i += 1
return np.array(rolling_mean) #np.array(rolling_std)
alist = [2,4,5,7,9,10,21,89,43,90,13,100,1,45]
x = pd.Series(alist)
rolling_mean_std(x, wd_size=3)
您可以尝试使用 Pandas rolling
函数并计算每个滚动 window 的标准差,并将每个标准差追加到列表中以获得滚动标准差。滚动方式相同。
例如:
wd_size = 3
alist = [2,4,5,7,9,10,21,89,43,90,13,100,1,45]
x = pd.Series(alist)
rolling_mean = []
rolling_std = []
for i in x.rolling(window = wd_size):
rolling_mean.append(np.mean(i))
rolling_std.append(np.std(i))