Many object attributes

I have a multidimensional array of objects, something like:

a = np.array([obj1,obj2,obj3]) 

Objects are instances of a class that has several attributes. Let them say that one of them is height, and one of them is length. To get the corresponding multidimensional array of lengths and heights, I do:

  lengths = np.array([obj1.length,obj2.length,obj3.length]) heights = np.array([obj1.height,obj2.height,obj3.height]) 

This starts to clutter up my code a lot. Is there a more efficient way to do this? For example, I had something like

  heights = a.height 

but obviously this does not work, because a is an array of my objects, not my object. But is there something similar that I can do that is efficient and pythonic? I tried something like

  for x in np.nditer(a,flags=['refs_ok']): print x.length 

to see what happens, but it won’t work, because nditer somehow returns a tuple.

Any ideas?

+4
source share
1 answer

You can vectorize the function:

 >>> import numpy >>> >>> class Obj(object): ... def __init__(self, x, y): ... self.x = x ... self.y = y ... >>> arr = numpy.array([Obj(1, 2), Obj(3, 4), Obj(5, 6)]) >>> >>> vectorized_x = numpy.vectorize(lambda obj: obj.x) >>> >>> vectorized_x(arr) array([1, 3, 5]) 

Although I'm not sure that you should really store an array of NumPy Python objects in the first place. Vectorize is no more efficient than a Python loop. It would be more convenient to store an array of (n + 1) -D, since we could easily extract the contents simply by slicing, which is a native operation, for example.

 >>> a = numpy.array([[(1, 2), (3, 4), (5, 6)], [(7, 8), (9, 10), (11, 12)], [(-13, -14), (-15, -16), (-17, -18)]]) >>> a[:,:,0] array([[ 1, 3, 5], [ 7, 9, 11], [-13, -15, -17]]) >>> a[:,:,1] array([[ 2, 4, 6], [ 8, 10, 12], [-14, -16, -18]]) 
+1
source

Source: https://habr.com/ru/post/1267029/


All Articles