Python numpy从类实例中查找平均值(遍历实例的元素)
假设我有一个包含许多类实例的数组Python numpy从类实例中查找平均值(遍历实例的元素),python,numpy,Python,Numpy,假设我有一个包含许多类实例的数组 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]) 但是我正在寻找
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))
我将使用python映射函数中的numpy对应项:
从所有属性
a
创建一个列表,并对其求平均值:
>>> np.average([x[0].a for x in a])
3.0
列表理解比np更快。对于本用例,矢量化:
%timeit np.average([x[0].a for x in a])
100000 loops, best of 3: 12 µs per loop
vs
很好,谢谢!顺便问一下,在这种情况下,索引是如何工作的。我的意思是,
x[0]。a
给了我们第一个元素,好吧。我们会使用x[1]。a
?(投票表决)不,你需要x[0]
,因为你的实例在[]
中,即[a(2,10)]
。对第二个元素使用np.average([x[0].b代表a中的x])
。除非你在子列表(第二维度)中放置多个实例:[A(2,10),A(3,15)]
。哦,是的。如果我有[A(2,10),A(3,4)]
,我会使用x[1]
,如果你能帮忙的话,我将不胜感激!谢谢
%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