Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.9k views
in Technique[技术] by (71.8m points)

python - Turning a standard deviation function to numpy form

I want to get the standard deviation for every nth number defined by number. So it takes the standard deviation of every 5th number in the list. So how would i be able to turn the function std down at the code below to the numpy format of np.std.

import numpy as np
number = 5
list_= np.array([457.334015,424.440002,394.795990,408.903992,398.821014,402.152008,435.790985,423.204987,411.574005,
404.424988,399.519989,377.181000,375.467010,386.944000,383.614990,375.071991,359.511993,328.865997,
320.510010,330.079010,336.187012,352.940002,365.026001,361.562012,362.299011,378.549011,390.414001,
400.869995,394.773010,382.556000])
for i in range(len(list_)-number):
     y_mean = sum(list_[i:i+number])/number     
     #Standard Dev function = square root((first list value - y_mean)+(second list value - y_mean) + (third list value - y_mean)/n-1)
     std = (sum([(k - y_mean)**2 for k in list_[i:i+number]])/(number-1))**0.5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It seems what you are trying to measure is the rolling standard deviation with a particular window. You can use a list comprehension combined with np.std:

>>> [list_[i:i+number].std() for i in range(0, len(list_)-number)]
[22.67653382706694,
 10.394077295510364,
 14.600764816599321,
 13.828019444486458,
 ...
 11.249337331453159,
 15.436611278024934,
 13.65945977634702]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...