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)

Apostolos
  • 7,763
  • 17
  • 80
  • 150
  • If my answer does not answer the question please post a small example of your expected input and output. – Daniel Oct 31 '13 at 16:34
  • It kinda did. But when tried in a larger array i still get division problems. Check this out http://stackoverflow.com/q/19711999/2349589 – Apostolos Oct 31 '13 at 16:53

1 Answers1

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]])
Daniel
  • 19,179
  • 7
  • 60
  • 74