有效地与numpy迭代 [英] efficiently Iterating with numpy

查看:127
本文介绍了有效地与numpy迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作的代码计算了数组y的句点p中每个元素的平均值

I made code that calculates the average value for each element in period p for array y

import numpy as np
p=4

y =np.asarray([146, 96, 59, 133, 192, 127, 79, 186, 272, 155, 98, 219])

c=len(y)/p
print c

a=[]
for i in range(1,c+1):
    s=y[p*(i-1):p*i]/np.mean(y[p*(i-1):p*i])
    a = np.append(a, s)
print a

b=[]
for i in range(c+1):
    s = np.mean(a[i::p])
    b = np.append(b, s)

print b

是否有更有效的方法这样做而不是使用append和for循环?我不需要两个数组只是b

Is there a more efficient way to do this instead of using append and the for loops? I do not need both arrays just b

推荐答案

实际上,你做了2d操作。如果添加了第二个维度(例如使用重新整形),则可以对第一个数组a进行评估:

In fact, you do a 2d operation. Your first array, a, can be evalueated if a second demension added (for example with reshape):

z = y.reshape(-1, p)
w = z/z.mean(axis=1).reshape(-1,1)
print w.flatten()
# [ 1.34562212  0.88479263  0.5437788   1.22580645  1.31506849  0.86986301
#   0.54109589  1.2739726   1.46236559  0.83333333  0.52688172  1.17741935]

您的第二个, b ,是以前结果的平均值:

Your second, b, is a mean of previous result:

print w.mean(axis=0)
# [ 1.37435207,  0.86266299,  0.53725214,  1.2257328 ]

更新

当你在评论中提到指数平滑时,你可能会对 pandas statsmodels 用于处理时间序列的包。请参阅pandas docs,其中包含一些有用的计算工具此ER 在问题跟踪器中提供了一些有关指数平滑实现的有用链接。

As you mention exponential smoothing in comments, you might be interested in pandas or statsmodels packages to deal with timeseries. See for example pandas docs with some useful computational tools and this ER in issue tracker for some useful links about exponential smoothing implementation.

这篇关于有效地与numpy迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆