[Numpy-discussion] swap elements in two arrays

Keith Goodman kwgoodman@gmail....
Sun Feb 7 10:16:23 CST 2010


On Sun, Feb 7, 2010 at 7:58 AM, Pauli Virtanen <pav@iki.fi> wrote:
> su, 2010-02-07 kello 10:39 -0500, Alan G Isaac kirjoitti:
> [clip]
>> I thought that if `to_swap` is a boolean array that `a[to_swap]`
>> will always own its own data.  Can that fail?
>
> Ok, I don't think it can fail, then. But it's a slightly dangerous idiom
> nevertheless...

I think it depends on how much you know about the inputs:

>> to_swap = np.array([True, True])

Good:

>> a = np.array([1, 2, 3])
>> b = a[1:].copy()
>>
>> a[to_swap], b[to_swap] = b[to_swap], a[to_swap]
>> a
   array([2, 3, 3])
>> b
   array([1, 2])

Bad:

>> a = np.array([1, 2, 3])
>> b = a[1:]
>>
>> a[to_swap], b[to_swap] = b[to_swap], a[to_swap]
>>
>> a
   array([2, 1, 2])
>> b
   array([1, 2])


More information about the NumPy-Discussion mailing list