Mavridis M.
Mavridis M.

Reputation: 115

Calculate an expression at specific array positions

I have two NumPy arrays dQ/dx and dQ/dt and I want to calculate V = (dQ/dt)/(dQ/dx) but only at the positions where both dQ/dx and dQ/dt are nonzero. If dQ/dx or dQ/dt are equal to zero then V = 0. In example dQ/dx = [ 0, 0, 0.2, 0.1], dQ/dt = [0.1 , 0 , 0.4 , 0], which should give V = [0, 0, 2, 0]. I could do that with a loop over all array elements but is there a more "NumPy" way to do it?

Upvotes: 1

Views: 81

Answers (1)

Tonechas
Tonechas

Reputation: 13733

Using numpy.logical_and and numpy.where is a possible way to go:

In [216]: import numpy as np

In [217]: dQdx = np.asarray([0, 0, 0.2, 0.1])

In [218]: dQdt = np.asarray([0.1 , 0, 0.4, 0])

In [219]: V = np.where(np.logical_and(dQdt, dQdx), dQdt/dQdx, 0)
<ipython-input-219-6cd6dde99502>:1: RuntimeWarning: divide by zero encountered in true_divide
  V = np.where(np.logical_and(dQdt, dQdx), dQdt/dQdx, 0)
<ipython-input-219-6cd6dde99502>:1: RuntimeWarning: invalid value encountered in true_divide
  V = np.where(np.logical_and(dQdt, dQdx), dQdt/dQdx, 0)

In [220]: V
Out[220]: array([0., 0., 2., 0.])

There are different methods to get rid of this ugly RuntimeWarning. For example, you could index the entries that are nonzero in both arrays through advanced indexing using the Boolean array np.logical_and(dQdt, dQdx) like this:

In [221]: V = np.zeros_like(dQdx)

In [222]: idx = np.logical_and(dQdt, dQdx)

In [223]: V[idx] = dQdt[idx]/dQdx[idx]

In [224]: V
Out[224]: array([0., 0., 2., 0.])

Upvotes: 2

Related Questions