Let’s say I have the following Numpy array:
array([[3, 5, 0], [7, 0, 2]])
I now want to add 2 where the value is not 0. What would be the fastest way to do this? I have to manipulate quite large multidimensional arrays?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It seems to me that:
should work.
(for the limited case of testing for non-zero-ness), you might be able to speed things up with (you’d need to
timeitto see):Of course, you can save yourself the mask calculation if you can reuse the same mask at different spots (which is a pretty restrictive constraint):
Of course, If this is enough of a bottleneck, you can always write a little C/Fortran extension to do this for you (using
Cythonorf2pyrespectively). This would avoid the overhead of mask creation.