2

now we have two arrays

a = [[1.,2.,3.,4.,5.,6.,7.,8.,9.],[9.,8.,7.,6.,5.,4.,3.,2.,1.]]

b = [[2.,2.,1.,2.,0.,2.,1.,2.,0.],[2.,2.,1.,2.,0.,2.,1.,2.,0.]]

Is there any fast way to achieve the following function: compare these two arrays by element, and change the array a[] in the following rule:

if a[i,j] > b[i,j]: 

    a[i,j] = a[i,j] 

else   

a[i,j] = 0

I know that a loop can do it, but I am wondering if there is any other faster way to do it.

1 Answer 1

3
import numpy as np
a = np.array([[1.,2.,3.,4.,5.,6.,7.,8.,9.],[9.,8.,7.,6.,5.,4.,3.,2.,1.]])
b = np.array([[2.,2.,1.,2.,0.,2.,1.,2.,0.],[2.,2.,1.,2.,0.,2.,1.,2.,0.]])

gr = np.greater(a,b)
a = np.multiply(a,gr)

The gr and a arrays become:

[[False False  True  True  True  True  True  True  True]
 [ True  True  True  True  True  True  True False  True]]

array([[ 0.,  0.,  3.,  4.,  5.,  6.,  7.,  8.,  9.],
       [ 9.,  8.,  7.,  6.,  5.,  4.,  3.,  0.,  1.]])
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.