Home > Mobile >  Dividing non-zero elements using Python
Dividing non-zero elements using Python

Time:06-14

I have an array A. I would like to divide the non-zero elements and obtain a new array B. The desired output is attached.

import numpy as np
A=np.array([[0,1,2],[4,0,8],[7,5,0]])
print([A])

The desired output is

B=[array([[0,1/1,1/2],[1/4,0,1/8],[1/7,1/5,0]])]

CodePudding user response:

With NumPy arrays, it's simple:

A = np.array([[0,1,2],[4,0,8],[7,5,0]])
# Create an array with zeroes with the same shape as A
B = np.zeros(A.shape)
# Update elements in B that are non-zero in A
B[A != 0] = 1/A[A != 0]

CodePudding user response:

Using numpy.where (you will get a RuntimeWarning though):

B = np.where(A, 1/A, 0)

or numpy.divide:

B = np.divide(1, A, out=np.zeros_like(A, dtype=float), where=A!=0)

CodePudding user response:

Try this :

try:
   B = A/2
except:
   pass
  • Related