3
matrix = np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]])
vector = np.array([0,0,0,0])

For vectors, you can edit every other element like so

vector[1::2] = 1

This gives

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

However;

matrix[1::2] = 1

yields

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

I would like the output

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

There is a brute force approach to take the shape of the array, flatten it, use [1::2], and reshape, but i'm sure there is a more elegant solution i am missing.

Any help would be appreciated.

  • For a few points of extra credit, is there a one-line method to yield a different pattern? instead of changing every other item, it would also be useful in my case to change two items, leave one the same, and so on. [0,0,0,0,0,0] -> [1,1,0,1,1,0] – william tepe Jan 14 '20 at 13:11
  • "For a few points of extra credit". Well if that isn't the boldest thing ever – sshashank124 Jan 14 '20 at 13:11

1 Answers1

6

You can do something similar with multidimensional indexing

>>> matrix
array([[0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0],
       [0, 0, 0, 0]])
>>> matrix[:,1::2] = 1
>>> matrix
array([[0, 1, 0, 1],
       [0, 1, 0, 1],
       [0, 1, 0, 1],
       [0, 1, 0, 1]])
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218