Python Numpy implements the method of exchanging two rows and two columns
- 2021-07-01 07:58:01
- OfStack
numpy should be a and commonly used package, but it has been checked in Baidu for a long time, and it has not been found how to exchange two columns (exchange two rows), so I checked other documents and found a way.
Exchange two lines
For example, a = np. array ([[1, 2, 3], [2, 3, 4], [1, 6, 5], [9, 3, 4]]), if you want to interchange lines 2 and 3, it seems simple, just write the code:
import numpy as np
a = np.array([[1,2,3],[2,3,4],[1,6,5], [9,3,4]])
tmp = a[1]
a[1] = a[2]
a[2] = tmp
The result of the operation is:
array([[1, 2, 3],
[1, 6, 5],
[1, 6, 5],
[9, 3, 4]])
The reason is because tmp = a [1] is not an copy of a [1], but an "alias", so we rewrite it as:
import numpy as np
a = np.array([[1,2,3],[2,3,4],[1,6,5], [9,3,4]])
tmp = np.copy(a[1])
a[1] = a[2]
a[2] = tmp
The running result is:
array([[1, 2, 3],
[1, 6, 5],
[2, 3, 4],
[9, 3, 4]])
The result is normal. Is there a simpler method, such as swap? After consulting, I found one of the simplest methods:
import numpy as np
a = np.array([[1,2,3],[2,3,4],[1,6,5], [9,3,4]])
a[[1,2], :] = a[[2,1], :]
Exchange two columns
Similar to the above:
a = np.array([[1,2,3],[2,3,4],[1,6,5], [9,3,4]])
a[:,[1,0,2]]
a
Get:
array([[1, 2, 3],
[2, 3, 4],
[1, 6, 5],
[9, 3, 4]])