假设我有一个充满了许多类实例的数组
a = np.array([[A(2, 10)], [A(3, 15)], [A(4, 14)]])如何使用numpy仅计算前几个A指数的平均值。
因此,2,3,4的平均值?
一种方法是:
thenew = np.zeros((a.size, a.size))
for idx, x in np.ndenumerate(a):
thenew[idx] = a[idx].a
result = np.average(thenew[:,0])但是我正在寻找一个使用numpy的更好的解决方案。
完整代码:
import numpy as np
class A():
def __init__(self, a, b):
self.a = a
self.b = b
class B():
def __init__(self, c, d, the_a):
self.c = c
self.d = d
self.the_a = the_a
def method(self, the_a):
thenew = np.zeros((self.the_a.size, self.the_a.size))
for idx, x in np.ndenumerate(self.the_a):
thenew[idx] = self.the_a[idx].a
return np.average(thenew[:,0])
a = np.array([[ A(2, 4)], [A(3,5)], [A(4,4)]])
b = B(1,1,a)
print(b.method(a))发布于 2017-02-03 17:01:06
根据所有属性a和创建一个列表,并对它们取平均值:
>>> np.average([x[0].a for x in a])
3.0对于这个用例,列表理解比np.vectorize更快:
%timeit np.average([x[0].a for x in a])
100000 loops, best of 3: 12 µs per loop与
%%timeit
func = np.vectorize(lambda x: x.a)
np.average(func(a))
10000 loops, best of 3: 26.2 µs per loop发布于 2017-02-03 17:00:49
我将使用来自python map函数的numpy的对应函数:numpy.vectorize
func = np.vectorize(lambda x: x.a)
np.average(func(a))https://stackoverflow.com/questions/42020164
复制相似问题