Joseph Romo
Joseph Romo

Reputation: 153

How to add a constant value to every other column in a numpy array?

I am having trouble adding a constant value to every other column in a numpy array. For example, Let's say that I have an array of zeros like:

import numpy as np    
a = np.zeros([100,10], dtype=np.int64)

and now I want to add a constant, say '50', to every element in every other column. This way I would expect to keep an array that is 10 columns by 100 rows that alternates as 0,50,0,50,0,50... etc

Upvotes: 0

Views: 5167

Answers (1)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You can do:

>>> a[:, ::2] += 50

For example:

>>> import numpy as np    
>>> a = np.zeros([5,10], dtype=np.int64)
>>> a[:, ::2] += 50
>>> a

array([[50,  0, 50,  0, 50,  0, 50,  0, 50,  0],
       [50,  0, 50,  0, 50,  0, 50,  0, 50,  0],
       [50,  0, 50,  0, 50,  0, 50,  0, 50,  0],
       [50,  0, 50,  0, 50,  0, 50,  0, 50,  0],
       [50,  0, 50,  0, 50,  0, 50,  0, 50,  0]], dtype=int64)

For both row and column you would do:

>>> a[::2, ::2] += 50

Upvotes: 3

Related Questions