Home > Blockchain >  How to divide a numpy array elementwise by another numpy array of lower dimension
How to divide a numpy array elementwise by another numpy array of lower dimension

Time:10-19

Let's say I have a numpy array [[0,1],[3,4],[5,6]] and want to divide it elementwise by [1,2,0]. The desired result will be [[0,1],[1.5,2],[0,0]]. So if the division is by zero, then the result is zero. I only found a way to do it in pandas dataframe with div command, but couldn't find it for numpy arrays and conversion to dataframe does not seem like a good solution.

CodePudding user response:

You could wrap your operation with np.where to assign the invalid values to 0:

>>> np.where(d[:,None], x/d[:,None], 0)

array([[0. , 1. ],
       [1.5, 2. ],
       [0. , 0. ]])

This will still raise a warning though because we're not avoiding the division by zero:

/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:1: 
RuntimeWarning: divide by zero encountered in `true_divide`
  """Entry point for launching an IPython kernel.

A better way is to provide a mask to np.divide with the where argument:

>>> np.divide(x, d[:,None], where=d[:,None] != 0)
array([[0. , 1. ],
       [1.5, 2. ],
       [0. , 0. ]])

CodePudding user response:

I have worked out this solution:

[list(x/y) if y != 0 else len(x)*[0,] for x, y in zip(a1, a2)]
  • Related