Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 609
Synthead Avatar asked Dec 28 '13 09:12

Synthead


2 Answers

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.

like image 60
NPE Avatar answered Oct 08 '22 14:10

NPE


Numpy slice notation supports doing this directly

f[:,:,0,4] = 1.0
like image 34
Andrew Walker Avatar answered Oct 08 '22 14:10

Andrew Walker