[Numpy-discussion] working with numpy object arrays

Moroney, Catherine M (398D) Catherine.M.Moroney at jpl.nasa.gov
Thu Jul 31 18:31:02 EDT 2014


In the example code below, is it possible to return an array of all the ".a"
values of the MyClass objects as stored in the object array "a"?

I am successfully able to retrieve the "a" attributes if I loop through the
array elements one by one, but I cannot do a whole-array operation to retrieve
the "a" attributes.

Is there any way to retrieve all the "a" attributes of the MyClass objects
all at once, or do I have to loop through all elements of "array" one-by-one?

Thanks for any help,

Catherine

import numpy

class MyClass(object):
   def __init__(self, a):
	self.a = a

   def add(self, b, c):
	self.a += b+c

   def return_a(self):
       return self.a

array = numpy.empty((2,2), dtype=object)
for i in xrange(0, 2):
    for j in xrange(0, 2):
	array[i,j] = MyClass(i+j)

for i in xrange(0, 2):
    for j in xrange(0, 2):
        array[i,j].add(i, j)
        print "(%i,%i) = %i" % (i, j, array[i,j].a)

try:
    array_a = array[:,:].a
    print "a values =",array_a
except AttributeError:
    print "Unable to access a attributes of array as a whole."

array_a = numpy.empty((2,2))
for i in xrange(0, 2):
    for j in xrange(0, 2):
        array_a[i,j] = array[i,j].a

print "a values =",array_a





More information about the NumPy-Discussion mailing list