By william tepe


2020-01-14 13:09:31 8 Comments

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.

1 comments

@Cory Kramer 2020-01-14 13:11:35

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

Related Questions

Sponsored Content

96 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6822024 View
  • 8405 Score
  • 96 Answer
  • Tags:   javascript arrays

36 Answered Questions

[SOLVED] Create ArrayList from array

53 Answered Questions

30 Answered Questions

[SOLVED] Finding the index of an item in a list

  • 2008-10-07 01:39:38
  • Eugene M
  • 3941952 View
  • 3235 Score
  • 30 Answer
  • Tags:   python list indexing

47 Answered Questions

[SOLVED] Sort array of objects by string property value

49 Answered Questions

[SOLVED] How to check if an object is an array?

39 Answered Questions

[SOLVED] Loop through an array in JavaScript

18 Answered Questions

[SOLVED] How to insert an item into an array at a specific index (JavaScript)?

40 Answered Questions

[SOLVED] For-each over an array in JavaScript

30 Answered Questions

[SOLVED] How to append something to an array?

Sponsored Content