[Numpy-discussion] slicing / indexing question

Brett Olsen brett.olsen@gmail....
Tue Sep 21 18:54:03 CDT 2010


On Tue, Sep 21, 2010 at 6:20 PM, Timothy W. Hilton <hilton@meteo.psu.edu> wrote:
> Hello,
>
> I have an indexing problem which I suspect has a simple solution, but
> I've not been able to piece together various threads I've read on this
> list to solve.
>
> 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.
>
> Any help greatly appreciated!
>
> Thanks,
> Tim

This works, although I imagine it could be streamlined.

In [1]: this_par = N.ones((2,4,4))
In [2]: idx = N.random.random((4,4)) > 0.5
In [3]: pars = N.arange(2) - 10
In [4]: this_par[:,idx] = N.tile(pars, (idx.sum(), 1)).transpose()
In [5]: idx
Out[5]
array([[ True, False, True, False],
         [False, False, True, True],
         [False, False, False, False],
         [False, False, False, False]], dtype=bool)
In [6]: this_par
Out[6]:
array([[[-10.,   1., -10.,   1.],
          [   1.,   1., -10., -10.],
          [   1.,   1.,    1.,   1.],
          [   1.,   1.,    1.,   1.]],
         [[ -9.,   1.,  -9.,   1.],
          [   1.,   1.,  -9.,  -9.],
          [   1.,   1.,    1.,   1.],
          [   1.,   1.,    1.,   1.]]])

Brett


More information about the NumPy-Discussion mailing list