Swap slices of Numpy arrays

Python correctly interprets the code as if you used additional variables, so the swapping code is equivalent to:

t1 = b[:,0,0]
t2 = a[:,0,0]
a[:,0,0] = t1
b[:,0,0] = t2

However, even this code doesn’t swap values correctly! This is because Numpy slices don’t eagerly copy data, they create views into existing data. Copies are performed only at the point when slices are assigned to, but when swapping, the copy without an intermediate buffer destroys your data. This is why you need not only an additional variable, but an additional numpy buffer, which general Python syntax can know nothing about. For example, this works as expected:

t = np.copy(a[:,0,0])
a[:,0,0] = b[:,0,0]
b[:,0,0] = t

Leave a Comment