0

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.

2 Answers 2

1

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. ]])
Sign up to request clarification or add additional context in comments.

Comments

0

I have worked out this solution:

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

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.