Home > Software design >  Is It possible to switch rows or columns between numpy arrays?
Is It possible to switch rows or columns between numpy arrays?

Time:06-30

I have the following numpy arrays

[[[0 0 1 0 0]
  [1 0 0 0 0]
  [0 0 1 0 0]]

 [[1 0 0 0 0]
  [0 0 1 0 0]
  [0 0 0 1 0]]]

am trying to switch rows between them, 1 row 2 rows it doesn't matter am trying to see if it's possible.

The output can be for the 1st row or 2nd row or 2 first rows respectively:

[[[0 0 1 0 0]             [[[0 0 1 0 0]             [[[1 0 0 0 0]x
  [1 0 0 0 0]               [0 0 1 0 0]x              [0 0 1 0 0]x
  [0 0 0 1 0]]x             [0 0 1 0 0]]              [0 0 1 0 0]]

 [[1 0 0 0 0]              [[1 0 0 0 0]              [[0 0 1 0 0]x
  [0 0 1 0 0]               [1 0 0 0 0]x              [1 0 0 0 0]x
  [0 0 1 0 0]]]x            [0 0 0 1 0]]]             [0 0 0 1 0]]]

Is it possible? If so How?

CodePudding user response:

You can switch values like rows on NumPy arrays with Python variable swap operator:

import numpy as np

m = np.array([[0, 0, 1, 0, 0],
[1, 0 ,0, 0, 0],
[0, 0, 1, 0, 0]])

n = np.array([[1, 0, 0, 0, 0],
 [0, 0, 1, 0, 0],
 [0, 0, 0, 1, 0]])

#m[:, 0], n[:, 0] = n[:, 0].copy(), m[:, 0].copy() #Only for columns
m[0], n[0] = n[0].copy(), m[0].copy() #For rows
print(m, n)

Output:

[[1 0 0 0 0]
 [1 0 0 0 0]
 [0 0 1 0 0]]

[[0 0 1 0 0]
 [0 0 1 0 0]
 [0 0 0 1 0]]
  • Related