0

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

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I am new to python and this is very helpful. I have not seen [:, before in an array, what does the colon and comma at the beginning of a[:, ::2] += 50 denote?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.