3

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?

2
  • One issue I see in the code is that get_a needs to return self.a, not a. Commented Jan 6, 2012 at 9:24
  • 1
    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 Commented Jan 6, 2012 at 9:42

2 Answers 2

0

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()
2
  • 1
    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. Commented Jan 6, 2012 at 22:11
  • Sadly this won't work if you intend to modify object array items. Commented Apr 10, 2017 at 11:46
0

Iterating over an array with nditer gives you views of the original array's cells as 0-dimensional arrays. For non-object arrays, this is almost equivalent to producing scalars, since 0-dimensional arrays usually behave like scalars, but that doesn't work for object arrays.

If you were determined to go through nditer for this, you could extract the elements from the 0-dimensional views with the item() method:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.