python - 根据另一个矩阵中的值移动一个矩阵中的值的有效方法

标签 python numpy scipy

所以我想改变 matrix_a 中的值根据 matrix_b 中的值.所以如果值在 matrix_b在位置 0,01 ,然后是 result_matrix 中的元素在 0,0应该是位于 1,1 的元素在 matrix_a .我已经使用以下代码进行了这项工作:

import numpy as np

matrix_a = np.matrix([[1, 2, 3],
                      [4, 5, 6],
                      [7, 8, 9]])
matrix_b = np.matrix([[1, 1, 0],
                      [0,-1, 0],
                      [0, 0, -1]])
result_matrix = np.zeros((3,3))


for x in range(matrix_b.shape[0]):
  for y in range(matrix_b.shape[1]):
    value = matrix_b.item(x,y)
    result_matrix[x][y]=matrix_a.item(x+value,y+value)

print(result_matrix)

这导致:
[[5. 6. 3.]
 [4. 1. 6.]
 [7. 8. 5.]]

现在这在大型矩阵上很慢,我觉得这可以使用 numpy 或 scipy 的函数之一进行优化。有人能告诉我如何更有效地做到这一点吗?

最佳答案

使用 np.indices

ix = np.indices(matrix_a.shape)
matrix_a[tuple(ix + np.array(matrix_b))]
Out[]: 
matrix([[5, 6, 3],
        [4, 1, 6],
        [7, 8, 5]])

作为忠告,尽量避免使用 np.matrix - 这只是为了兼容旧的 MATLAB代码,并打破了很多 numpy职能。 np.array 99% 的时间都可以正常工作,其余时间 np.matrix会混淆核心 numpy用户。

关于python - 根据另一个矩阵中的值移动一个矩阵中的值的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59715074/

相关文章:

python - 重构文本中的鹈鹕外部图像

python - 矢量化 : Limit the increase in value between two subsequent numbers in Series (or list/array/whatever)

Python numpy 屏蔽数组初始化

python - 如何在 SciPy 的短时傅立叶变换中设置频率网格?

python - 如何测试一个类是否显式定义了 __gt__?

python - 我可以通过 virtualenv/virtualenvwrapper 使用其他 python 实现吗?

python - 在 Python 中获取包含 NaN 的列表的平均值

python - 为什么 numpy.random.dirichlet() 不接受多维数组?

python scipy.odrpack.odr 示例(带有示例输入/输出)?

numpy - 多项朴素贝叶斯与 scikit-learn 用于连续和分类数据