python - Numpy 数组替代 for 循环

标签 python arrays numpy vectorization

假设我有一个数组 A[i,j],我想通过执行以下操作来计算新的数量 B[i,j]:

for i in arange(1, n):
    B[i,j+1] = a*A[i-1,j] + b*A[i,j]+ c*A[i+1,j]

我可以使用什么 numpy 功能将其转换为纯数组操作?

我正在考虑 np.cumprod 但不清楚如何将系数纳入计算中。

A.shape 将为 (n+1, j)。

最佳答案

定义A_left = A[:-2, :]A_middle = A[1:-1, :]A_right = A[2: ,:]

然后B = a*A_left + b*A_middle + c*A_right

关于python - Numpy 数组替代 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33127245/

相关文章:

python - 从 Django 1.8 获取 TemplateDoesNotExist

python - 在 Linux 中将文件作为参数传递

python - 按每行中的列数对 csv 进行排序

java - 将字符串数组拆分为列 java

python - python 3 中的 np.genfromtxt 错误

python - 带正则化的 Numpy 线性回归

python - 使用 SciPy/Numpy 在 Python 中连接稀疏矩阵

python - 如何将多个查询集组合/合并为单个查询集 django

java - 无法处理二维对象数组

Python 'list indices must be integers, not tuple"错误