2

对于给定(对象)数组的每个元素调用函数的结果,我有哪些选择?

我现在要做的是:

object_array # an array whose elements are objects
result_array=scipy.reshape( [o.f() for o in object_array.flat], object_array.shape )

我的情况类似于有object_array[i,j]一个实例scipy.stats.norm,其中分布的参数对于不同的元素是不同的。并且scipy.stats.norm.rvs()f()我想要调用的那个。请注意, 的大小object_array可能非常大(最多大约 1000x1000),所以我担心这是次优的,因为我在调用reshape.

4

1 回答 1

1

你的方法似乎很合理。我尝试了一个更好的使用np.nditer,但你的仍然是两倍快:

import numpy as np
class Foo():
    def foo(self):
        return np.random.random()

a = np.empty((10,10), dtype=object)
for ind,v in np.ndenumerate(a):
    a[ind] = Foo()

def evaluate_and_reshape(a, shape):
    it = np.nditer( op    = [a.reshape(shape),None],
                    flags = ['multi_index','refs_ok'],
                    op_flags = [['readonly'],
                                ['writeonly','allocate']],
                    op_dtypes = [object, float],
                    itershape = (shape)
                  )
    while not it.finished:
        ind = it.multi_index
        it.operands[1][ind] = it.operands[0][ind].foo()
        it.iternext()
    return it.operands[1]

def sol1():
    return evaluate_and_reshape(a,(20,5))

def sol2():
    return np.reshape( [o.foo() for o in a.flat], (20,5) )

定时:

timeit sol1()
#10000 loops, best of 3: 110 us per loop
timeit sol2()
#10000 loops, best of 3: 54.8 us per loop
于 2013-08-01T17:35:09.527 回答