Skip to content Skip to sidebar Skip to footer

New Numpy Array From Attribute Of Objects In Another Numpy Array

Is there a way to do an element-wise attribute extraction from a numpy array? For example, say I have: import numpy as np class foo(): def __init__(self, value): self.

Solution 1:

I think the fastest way will be to combine Python's operator.attrgetter with numpy's np.frompyfunction - the first gives a fast, native code inlined, way to retrieve an object's attribute. The second, transforms an ordinary Python function into a Numpy's broadcast function, which can process an entire array in a single call -

so, your call is:

from operator import attrgetter
import numpy as np
# code to build obj_array
...
bar_array_easy_way = np.frompyfunc(attrgetter("bar"), 1, 1)(obj_array)

Quickly comparing it against using fromtiterator built a 1 million int array from my objects in half the time - besides, fromiterator can't build arrays with dtype=object - just fixed size elements.

Note that attrgetter itself is rather a "function factory" - it takes an attribute name, and returns a function that will take any object and return that attribute. That returned function we pass in turn, to frompyfunc - which takes other 2 arguments in order to allow numpy to make its broadcasting magic: the number of input arguments and the number of return results for our function.


Solution 2:

You can create your new array as:

bar_array = np.reshape(
    np.fromiter((x.bar for x in obj_array.flat), dtype=float),
    obj_array.shape)

Alter the dtype to whatever you'd please.


Post a Comment for "New Numpy Array From Attribute Of Objects In Another Numpy Array"