1

I have an array with dimensions (10x10) and i want to create another one (10x10). Lets say the first one is called A and the second one B. I want B to have 0 value if the value of A is zero respectively or another value(specified by me) lets say c if the value of A is not zero.

something like that

B[i] = A[i] == 0 ? 0 : c

Can this be done automatically by numpy?Like this:

B = A == 0 ? 0:c

or must i traverse the arrays element by element?

Editing for more info:

I have a numpy Array(10x10) A and one B same dimensions. I created another one

dif = A-B

now A has zero elements and B two, ergo dif has some zero elements

I want to create another one C numpy array where if A has element zero the value in C will be zero but if not then the value would be dif/A (the division of the elements)

2
  • If my answer does not answer the question please post a small example of your expected input and output. Commented Oct 31, 2013 at 16:34
  • It kinda did. But when tried in a larger array i still get division problems. Check this out stackoverflow.com/q/19711999/2349589 Commented Oct 31, 2013 at 16:53

1 Answer 1

3

You can use np.where:

>>> A
array([[3, 2, 0, 3],
       [0, 3, 3, 0],
       [3, 1, 1, 0],
       [2, 1, 3, 1]])

>>> np.where(A==0, 0, 5)
array([[5, 5, 0, 5],
       [0, 5, 5, 0],
       [5, 5, 5, 0],
       [5, 5, 5, 5]])

This basically says where A==0 place 0 else place 5. The second and third arguments can be multidimensional arrays as long as they match the same dimension as your mask.

C
array([[7, 8, 8, 6],
       [5, 7, 5, 5],
       [6, 9, 9, 9],
       [9, 7, 5, 8]])

np.where(A==0 ,0, C)
array([[7, 8, 0, 6],
       [0, 7, 5, 0],
       [6, 9, 9, 0],
       [9, 7, 5, 8]])

D
array([[145, 179, 123, 129],
       [173, 156, 108, 130],
       [186, 162, 157, 197],
       [178, 160, 176, 103]])

np.where(A==0, D, C)
array([[  7,   8, 123,   6],
       [173,   7,   5, 130],
       [  6,   9,   9, 197],
       [  9,   7,   5,   8]])
Sign up to request clarification or add additional context in comments.

2 Comments

Yes but this is changing data on the same array. I want where A==0 B=0 else B=c
Is 'c' a numpy array? If so you can replace 5 with c as long as c has the same dimensions as A.

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.