# [Numpy-discussion] slicing / indexing question

Anne Archibald aarchiba@physics.mcgill...
Wed Sep 22 13:22:50 CDT 2010

```On 21 September 2010 19:20, Timothy W. Hilton <hilton@meteo.psu.edu> wrote:

> I have an 80x1200x1200 nd.array of floats this_par.  I have a
> 1200x1200 boolean array idx, and an 80-element float array pars.  For
> each element of idx that is True, I wish to replace the corresponding
> 80x1x1 slice of this_par with the elements of pars.
>
> I've tried lots of variations on the theme of
>>>>this_par[idx[np.newaxis, ...]] = pars[:, np.newaxis, np.newaxis]
> but so far, no dice.

In [1]: A = np.zeros((2,3,5))

In [2]: B = np.array([1,2])

In [3]: C = np.zeros((3,5), dtype=np.bool)

In [4]: C[1,1] = True

In [5]: C[2,3] = True

In [6]: C
Out[6]:
array([[False, False, False, False, False],
[False,  True, False, False, False],
[False, False, False,  True, False]], dtype=bool)

In [7]: A[:,C] = B[:,np.newaxis]

In [8]: A
Out[8]:
array([[[ 0.,  0.,  0.,  0.,  0.],
[ 0.,  1.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  1.,  0.]],

[[ 0.,  0.,  0.,  0.,  0.],
[ 0.,  2.,  0.,  0.,  0.],
[ 0.,  0.,  0.,  2.,  0.]]])

The key is that indexing with C replaces the two axes C is indexing
with only one; boolean indexing necessarily flattens the relevant
axes. You can check this with (e.g.) A[:,C].shape.

Be careful with these "mixed" indexing modes (partly fancy indexing,
partly slicing) as they can sometimes seem to reorder your axes for
you:

In [16]: np.zeros((2,3,7))[:,np.ones(5,dtype=int),np.ones(5,dtype=int)].shape
Out[16]: (2, 5)

In [17]: np.zeros((2,3,7))[np.ones(5,dtype=int),:,np.ones(5,dtype=int)].shape
Out[17]: (5, 3)

In [18]: np.zeros((2,3,7))[np.ones(5,dtype=int),np.ones(5,dtype=int),:].shape
Out[18]: (5, 7)

Anne
```