2

I got the below numpy array:

a = np.array([
       [ 0.87142134, -1.99712722, -0.17742774],
       [-0.15155389,  0.0450012 ,  0.23662928],
       [-0.84674329,  2.34415168,  1.23702494],
       [ 1.98923065, -0.02327895,  0.21864032],
       [ 1.62936827,  1.39849021,  1.04613713]])

And I would like to swap the values between position 0 and position 1, which is something like this:

array([[-1.99712722, 0.87142134,  -0.17742774],
       [0.0450012, -0.15155389,   0.23662928],
       [2.34415168, -0.84674329,    1.23702494],
       [-0.02327895, 1.98923065,   0.21864032],
       [1.39849021, 1.62936827,  1.04613713]])

I tried the code as follows, however, it failed:

b = a.T
b[1], b[0] = b[0], b[1]

How could I achieve this result?

Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
Hang
  • 197
  • 1
  • 11
  • Does this answer your question? [Swapping columns in a numpy array?](https://stackoverflow.com/questions/4857927/swapping-columns-in-a-numpy-array) – Michael Szczesny May 10 '22 at 10:19

1 Answers1

2

you can use:

a[:, [0,1]] = a[:, [1,0]]

output:

array([[-1.99712722,  0.87142134, -0.17742774],
       [ 0.0450012 , -0.15155389,  0.23662928],
       [ 2.34415168, -0.84674329,  1.23702494],
       [-0.02327895,  1.98923065,  0.21864032],
       [ 1.39849021,  1.62936827,  1.04613713]])
mozway
  • 194,879
  • 13
  • 39
  • 75