python - 计算特定数组位置的表达式

标签 python arrays numpy

我有两个 NumPy 数组 dQ/dxdQ/dt,我想计算 V = (dQ/dt)/(dQ/dx) 但仅限于dQ/dxdQ/dt均非零的位置。如果dQ/dxdQ/dt等于零,则V = 0。在示例中,dQ/dx = [ 0, 0, 0.2, 0.1]dQ/dt = [0.1 , 0 , 0.4 , 0],应给出 V = [0, 0, 2, 0] 。 我可以通过循环遍历所有数组元素来做到这一点,但是有没有更“NumPy”的方法来做到这一点?

最佳答案

使用numpy.logical_andnumpy.where是一种可能的方法:

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

有不同的方法可以摆脱这个丑陋的RuntimeWarning。例如,您可以使用 bool 数组 np.ological_and(dQdt, dQdx) 通过高级索引对两个数组中非零的条目进行索引,如下所示:

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

关于python - 计算特定数组位置的表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36896202/

相关文章:

python - Pyqt - 从模型中获取 CSV

python - 通过 Python 进行音频/视频广播

python - 具有嵌套灵活类型(np.void类型)的索引结构numpy数组

python - 从 python Counter 字典到 nd numpy 数组

python 3 : clean example for inheritance & abstract methods?

python - 在 rpy 中传递 R 函数参数

python - 将 math.ceil 应用于 python 中的数组

javascript - 打印对象数组

python - 使用皮马印第安人糖尿病发病数据集的神经网络

python - 执行操作时恢复列