Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a constant to a slice of array

Trying to mutate a slice of an array, adding a constant to elements with odd indices. But this must be a copy, not the original array which is assigned, since this doesn’t change the array:

times = np.arange(10)
times[1::2] = times[1::2] + 0.5

It’s curious since this works:

times[1::2] = -1

Why is the slice a copy?
How to make it work like expected?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use addition assignment (with type agreement):

a = np.arange(10).astype(float)
a[1::2] += 0.5

array([0. , 1.5, 2. , 3.5, 4. , 5.5, 6. , 7.5, 8. , 9.5])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading