2

I want to do an assignment to a multidimensional array where each element of the array is 3 short integers:

a = ndarray([3,3,3], dtype='u2,u2,u2')
a[2,2,2] = [1,2,3]

Traceback (most recent call last): File "", line 1, in a[2,2,2] = [1,2,3] TypeError: expected a readable buffer object

I am going to be using a large array and would like to get direct indexing into the array for performance. What is a good way to do this in python?

Thanks for any insight into how to do this?

1 Answer 1

1

The elements of an array of dtype='u2,u2,u2' are a tuple of three shorts, not a list of three shorts. So:

a[2,2,2] = (1,2,3)

(The parens are of course not necessary, but I used them to make it obvious this is a tuple.)

You can also pass it an array if you want:

a[2,2,2] = np.array([1,2,3])

Of course the error message here certainly could be better… What it's actually complaining about is something deeper than what you'd expect, and it doesn't help you debug the problem.

2
  • Thanks for the comment.That helps. If I am getting a list as a parameter in to a function, do I have to convert it to a tuple to do the assignment to the array? What is the most efficient way to assign 3 numerical coordinates coming as a function parameter to an array element? Thanks Commented Jul 17, 2013 at 22:58
  • I'm not sure whether calling a[x,y,z] = tuple(foo) is faster or slower than a[x,y,z] = np.array(foo); if it matters, test it. But I doubt it will matter. If it matters, it's probably because you're doing it in a big loop—in which case the fact that you're looping in Python instead of vectorizing is the real problem you need to solve.
    – abarnert
    Commented Jul 17, 2013 at 23:08

Your Answer

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

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