Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a multi-dimensional array of objects. I want to interate over the objects using the nditer iterator. Here is a code example:

import numpy as np

class Test:
    def __init__(self,a):
        self.a = a
    def get_a(self):
        return self.a

b = np.empty((2,3),dtype = object)

t_00 = Test(0)
t_01 = Test(1)
t_11 = Test (11)

b[0,0] = t_00
b[0,1] = t_01
b[1,1] = t_11

for item in np.nditer(b,flags = ["refs_ok"]):
    if item:
        print item.get_a()

I would expect the "item" to contain the object reference that I can use to access data. However I am getting the following error:AttributeError: 'numpy.ndarray' object has no attribute 'get_a' My question is how can I go thru the array to access the object in the array?

share|improve this question
    
One issue I see in the code is that get_a needs to return self.a, not a. –  ditkin Jan 6 '12 at 9:24
    
You are right. However, I have the basic problem that I cannot access the "test object" at all. It seems that each "item" is referring to a numpy.ndarray –  user963386 Jan 6 '12 at 9:42
add comment

1 Answer

up vote 0 down vote accepted

The array.flat method of iteration will work, and can confirm that this works as you'd expect

for item in b.flat:
    if item:
        print item.get_a()
share|improve this answer
    
Thanks Jason! However I am still trying to find out how to use the nditer iterator. It works all right if I have an array with regular numbers. When I have objects, there is a problem. But I can see that nditer is reurning the right object address but may be with the wrong type. –  user963386 Jan 6 '12 at 22:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.