0

I have a numpy array with zeros and non-zeros and shape (10,10). To a subpart of this array I need to add a certain value, where initial value is not zero.

a[2:7,2:7] += 0.5 #But with a condition that a[a!=0]

Currently, I do it in a rather cumbersome way, by first making a copy of the array and modifying the second array consistently and then copying back to the first.

b = a.copy()
b[b!=0] = 1
b[2:7,2:7] *= 0.5
b[b ==1] =0
a += b

Is there more elegant way to achieve this?

3
  • 1
    b = a[2:7,2:7] and then b[b!=0] += 0.5. Test it with print(a). Commented Feb 16, 2019 at 11:47
  • Great it works!! Thanks! Commented Feb 16, 2019 at 11:53
  • I forgot that unless you make a copy, b would still refer to a. Too much mutability, but sometime you can use for your good. Commented Feb 16, 2019 at 11:54

1 Answer 1

2

As Thomas Kühn, correctly wrote in the comment, its good enough to create a reference to that subpart of the array and modify it. So the following does the job.

b = a[2:7,2:7]
b[b!=0] += 0.5
Sign up to request clarification or add additional context in comments.

Comments

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.