In Python I can exchange 2 variables by mean of multiple affectation; it works also with lists:
l1,l2=[1,2,3],[4,5,6] l1,l2=l2,l1 print(l1,l2) >>> [4, 5, 6] [1, 2, 3]
But when I want to exchange 2 rows of a numpy array (for example in the Gauss algorithm), it fails:
import numpy as np a3=np.array([[1,2,3],[4,5,6]]) print(a3) a3[0,:],a3[1,:]=a3[1,:],a3[0,:] print(a3) >>> [[1 2 3] [4 5 6]] [[4 5 6] [4 5 6]]
I thought that, for a strange reason, the two columns were now pointing to the same values; but it's not the case, since a3[0,0]=5
after the preceeding lines changes a3[0,0] but not a3[1,0].
I have found how to do with this problem: for example a3[0,:],a3[1,:]=a3[1,:].copy(),a3[0,:].copy()
works. But can anyone explain why exchange with multiple affectation fails with numpy rows? My questions concerns the underlying work of Python and Numpy.
To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.
So, to swap two rows of a matrix, left-multiply it by the appropriately-sized idenity matrix that has had its corresponding rows swapped. For example, to swap rows 0 and 2 of a 3×n matrix, left-multiply it by [001010100].
This works the way you intend it to:
a3[[0,1]] = a3[[1,0]]
The two separate assignments in the tuple assignment are not buffered with respect to eachother; one happens after the other, leading the overwriting your observe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With