1

Here is a section of code which is giving me a different answer to what I would expect. The line: print list(x) does what I expect. I would expect the line: print random_array[list(x)] to return the value of that element in the array but it returns three arrays. If for example list(x) returns [9, 8, 7] then random_array[9, :, :], random_array[8, :, :], random_array[7, :, :] will be printed. Can someone please explain to me why this is? And how I can get the expected answer?

import numpy as np
import itertools

random_array = np.random.randint(0, 9, (10, 10, 10))
my_iterator = itertools.product(range(10),range(10),range(10))

for x in my_iterator:
    print list(x)
    print random_array[list(x)]
3
  • I have closed my answer. Numpy does support random_array[(2,3,3)] Commented Feb 24, 2012 at 14:44
  • It supports it but doesnt do what OP expects. Commented Feb 24, 2012 at 14:46
  • Reopened my answer; figured it out. Commented Feb 24, 2012 at 14:47

4 Answers 4

3

You are passing in a list rather than a tuple:

# What you are doing
random_array[[2, 3, 3]]  # semantics: [arr[2], arr[3], arr[3]]

# What you want to be doing
random_array[(2, 3, 3)]  # semantics: arr[2][3][3], same as arr[2,3,3]

In short: do not cast your tuples to lists using list(...).

Sign up to request clarification or add additional context in comments.

7 Comments

I see that I am passing in a list rather than I slice. So: random_array[[2, 3, 3]]
Can you expand the tuple like: random_array[*(2, 3, 3)]
@Marcin: that's exactly what I was in the process of testing
I believe this answer explains more than the chosen answer.
Here are some docs if anyone wants to know more about numpy indexing. docs.scipy.org/doc/numpy/reference/arrays.indexing.html
|
1

I think what you want is:

print random_array[x[0], x[1], x[2]]

If you pass a list as index to numpy it will iterate trough the index list and get you that slice of elements. For example:

>>> test = numpy.array(range(10))
>>> idx = [1, 2, 3]
>>> test[idx]
array([1, 2, 3])

Comments

1

How about

print random_array[x]

When you pass a list, advanced indexing is taking place, which is not what you want.

Comments

0

You say:

I would expect the line: print random_array[list[x]) to return the value of that element in the array

But your code does not contain such a line. I expect this is the cause of your problem.

4 Comments

Stop being such a pendant. Clearly he's referring to the last line of his extract.
Yes that was a typo. I meant "I would expect the line: print random_array[list(x)]" and I have edited the question accordingly.
@DavidKemp: Tell that to your python interpreter.
Marcin has a point I guess. Precision is important in all aspects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.