简体   繁体   中英

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

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.

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. ]])

我已经制定了这个解决方案:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM