Python, Numpy
有没有一种更紧凑的方法来操作数组元素,而不必使用标准的for循环?
例如,考虑下面的函数:
filterData(A):
B = numpy.zeros(len(A));
B[0] = (A[0] + A[1])/2.0;
for i in range(1, len(A)):
B[i] = (A[i]-A[i-1])/2.0;
return B;
Numpy有一个diff操作符,可用于numpy数组和Python原生数组。你可以将代码重写为:
def filterData(A):
B = numpy.zeros(len(A));
B[1:] = np.diff( A )/2.0
B[0] = (A[0] + A[1])/2.0;
return B
还有numpy.ediff1d
,它允许您使用to_end
和to_begin
参数显式地在差分前缀或后缀中添加内容,例如:
>>> import numpy as np
>>> a = np.arange(10.)
>>> diff = np.ediff1d(a,to_begin = a[:2].sum()) / 2.
>>> diff
array([ 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5])
>>> diff.size
10
B[1:]=(A[1:]-A[:-1])/2.0
可以替换整个循环。 - Jaime