1

I have an array in three dimensions (a, b, c) and I need to modify the positions c indexed by an array in two dimensions (a, b).

I wrote a code that works as expected, but does anyone know if there is a way to solve this problem without the for loop?

import numpy as np
arr = np.random.randn(100, 5, 2)
mod = np.random.randn(100, 5)
ids = np.random.randint(0, 2, size=[100,5])
for i in range(100):
    for j in range(5):
        arr[i,j,ids[i,j]] = mod[i,j]
2
  • Hi. I don't understand how ids = np.random.randint(0, 2, size=[100,5]) is helping you. It generates a 2D array filled randomly with 0s and 1s, which you then use to define which slice mod[i, j] gets assigned to. So in short when you assign mod[i, j], on your last line, you are assigning it randomly to point [i,j,0] or [i,j,1] Are you doing this on purpose? If so, I don't understand what you are trying to do so my answer probably isn't what you are looking for. If this isn't a bug, could you please edit your answer to clarify your question? Thanks. Commented Mar 28, 2021 at 13:45
  • Hi. Thank you for your attention. That code is just a simplification of my problem. I defined arr, mod and ids as random to be able to run as an example. The short story is I am using an evolutionary algorithm in machine learning, and my code is taking much time to finish because the number of generations is so big. Then, I am trying to optimize it by eliminating loops. In this case, I need to change arr putting mod in the positions according to ids. If I get this, I will eliminate many loops in my code. I am reading the links in your answer right now. Commented Mar 28, 2021 at 14:36

2 Answers 2

1

You can refer to and set each slice of the array directly. I think this code shows the behaviour you are asking about:

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print(arr[:,:,2])
# Output: 
#[[ 3  6]
# [ 9 12]]

new2DSlice = np.array([[23, 26], [29, 32]])
arr[:,:,2] = new2DSlice
print(arr[:,:,2])
# Outupt:
#[[23 26]
# [29 32]]

arr[:,:,2] refers to the third slice of the array and, in this example, sets it directly.

You can read about NumPy's array indexing and array slicing on W3Schools.

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

Comments

1

I got with this:

import numpy as np
arr = np.random.randn(100, 5, 2)
mod = np.random.randn(100, 5)
ids = np.random.randint(0, 2, size=[100,5])
x = np.arange(100)
y = np.arange(5)
arr[x[:,None],y,ids] = mod

Comments

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.