[Numpy-discussion] slicing / indexing question
josef.pktd at gmail.com
josef.pktd at gmail.com
Tue Sep 21 20:04:26 EDT 2010
On Tue, Sep 21, 2010 at 7:54 PM, Brett Olsen <brett.olsen at gmail.com> wrote:
> On Tue, Sep 21, 2010 at 6:20 PM, Timothy W. Hilton <hilton at 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.]]])
introspection works easier with an example
indexing with slice and boolean seems to flatten the boolean part,
then we need only one newaxis ? seems to work
>>> this_par[:,idx].shape # = N.tile(pars, (idx.sum(), 1)).transpose()
(2, 8)
>>> idx
array([[ True, False, False, False],
[ True, True, True, False],
[ True, True, False, False],
[ True, False, True, False]], dtype=bool)
>>> this_par[:,idx] = pars[:,N.newaxis]
>>> this_par
array([[[-10., 1., 1., 1.],
[-10., -10., -10., 1.],
[-10., -10., 1., 1.],
[-10., 1., -10., 1.]],
[[ -9., 1., 1., 1.],
[ -9., -9., -9., 1.],
[ -9., -9., 1., 1.],
[ -9., 1., -9., 1.]]])
Josef
> Brett
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
More information about the NumPy-Discussion
mailing list