Synthead
Synthead

Reputation: 2321

Python/Numpy: Setting values to index ranges

Using Numpy, I can create a 5-dimensional array like this:

>>> faces = numpy.zeros((3, 3, 3, 6, 3))

I want (all indexes, all indexes, 0, 4) to be set to (1., 1., 1.). Is this possible by only using Numpy (no Python loops)?

Upvotes: 6

Views: 13304

Answers (2)

NPE
NPE

Reputation: 500167

Both of the following will do it:

faces[:,:,0,4] = 1

faces[:,:,0,4] = (1, 1, 1)

The first uses the fact that all three values are the same by having NumPy broadcast the 1 to the correct dimensions.

The second is a little bit more general in that you can assign different values to the three elements.

Upvotes: 6

Andrew Walker
Andrew Walker

Reputation: 42440

Numpy slice notation supports doing this directly

f[:,:,0,4] = 1.0

Upvotes: 2

Related Questions