2

I have an n-dimensional bool numpy array. I want to invert the bool value of a random item in the array. Inverting is easy, but I'm not sure how to best index a random element. I can generate a list of random positions along the n dimensions

indices = [np.random.randint(n) for n in array.shape]

However, how do I use that to index the corresponding element? array[indices] fetches elements at indices along the first dimension. array[*indices] does not work. I could do something like

a = array[indices[0]]
for index in indices[1:]:
    a = a[index]

but I'd like to avoid loops. Is there a more elegant solution?

1
  • 1
    [(*indices,)] will work fine Commented Sep 4, 2021 at 19:00

1 Answer 1

2

I know this sound too simple, but use a tuple instead of a list for the index. There's some documentation about why this is in the Numpy docs, but (at least for me) the significance of tuples isn't immediately obvious (even though it was quite clear and there's a big warning box about this).

import numpy as np

np.random.seed(201)

A = np.random.choice(a=[False, True], size=(2,2))

# make it a Tuple
index = tuple(np.random.randint(n) for n in A.shape)

print(A)
# [[False True]
#  [False  True]]

print(index)
# (0, 1)

print(A[index])
# True

A[index] = ~A[index]
print(A)

# [[False  False]
#  [False  True]]
Sign up to request clarification or add additional context in comments.

4 Comments

Why not just np.randint(a.shape)?
Yeah, @MadPhysicist that's a cleaner way to make the array. I suppose the main point of the answer is that would still need to be turned into a tuple to use it the way the OP wants and avoid triggering advanced indexing.
Thanks, that was it. I don't find this syntax to be very intuitive but I will sure remember it now.
It helps me to remember that a[3,4,2] is really a[(3,4,2)]. The index is a tuple, with one element per dimension. It's the comma that creates the tuple, the () are not always necessary.

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.