User guide

NumPy User Guide, Release 1.9.0
>>> y[:,np.newaxis,:].shape
(5, 1, 7)
Note that there are no new elements in the array, just that the dimensionality is increased. This can be handy to
combine two arrays in a way that otherwise would require explicitly reshaping operations. For example:
>>> x = np.arange(5)
>>> x[:,np.newaxis] + x[np.newaxis,:]
array([[0, 1, 2, 3, 4],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[3, 4, 5, 6, 7],
[4, 5, 6, 7, 8]])
The ellipsis syntax maybe used to indicate selecting in full any remaining unspecified dimensions. For example:
>>> z = np.arange(81).reshape(3,3,3,3)
>>> z[1,...,2]
array([[29, 32, 35],
[38, 41, 44],
[47, 50, 53]])
This is equivalent to:
>>> z[1,:,:,2]
array([[29, 32, 35],
[38, 41, 44],
[47, 50, 53]])
2.4.9 Assigning values to indexed arrays
As mentioned, one can select a subset of an array to assign to using a single index, slices, and index and mask arrays.
The value being assigned to the indexed array must be shape consistent (the same shape or broadcastable to the shape
the index produces). For example, it is permitted to assign a constant to a slice:
>>> x = np.arange(10)
>>> x[2:7] = 1
or an array of the right size:
>>> x[2:7] = np.arange(5)
Note that assignments may result in changes if assigning higher types to lower types (like floats to ints) or even
exceptions (assigning complex to floats or ints):
>>> x[1] = 1.2
>>> x[1]
1
>>> x[1] = 1.2j
<type ’exceptions.TypeError’>: can’t convert complex to long; use
long(abs(z))
Unlike some of the references (such as array and mask indices) assignments are always made to the original data in
the array (indeed, nothing else would make sense!). Note though, that some actions may not work as one may naively
expect. This particular example is often surprising to people:
>>> x = np.arange(0, 50, 10)
>>> x
2.4. Indexing 25