Home > Blockchain >  Swaping elements in an array
Swaping elements in an array

Time:05-11

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?

CodePudding user response:

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]])
  • Related