[Numpy-discussion] swap elements in two arrays
Alan G Isaac
aisaac@american....
Sun Feb 7 12:42:20 CST 2010
On 2/7/2010 11:16 AM, Keith Goodman wrote:
> 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])
So that is an important point:
if `a` and `b` share data, the
"swap" is not well defined.
But that affects the alternative idiom as well:
>>> to_swap
array([ True, True], dtype=bool)
>>> a = np.array([1, 2, 3])
>>> b = a[1:]
>>> temp = a.copy()
>>> a[to_swap] = b[to_swap]
>>> b[to_swap] = temp
>>> a, b
(array([2, 1, 2]), array([1, 2]))
Thanks,
Alan
More information about the NumPy-Discussion
mailing list