我在向现有二维数组添加子数组时遇到问题。 我实际上是 numpy 和 python 的新手,并且来自 MATLAB,这是一件微不足道的事情。 请注意,在我的问题中,通常 a 是一个大矩阵。
import numpy as np
a = np.array(arange(16)).reshape(4,4) # The initial array
b = np.array(arange(4)).reshape(2,2) # The subarray to add to the initial array
ind = [0,3] # The rows and columns to add the 2x2 subarray
a[ind][:,ind] += b #Doesn't work although does not give an error
我环顾四周发现以下方法可行
a[:4:3,:4:3] += b
但是我如何预先定义 ind 呢? 另外,如果 ind 由两个以上无法用步幅表示的数字组成,如何定义?例如 ind = [1, 15, 34, 67]
最佳答案
处理一般情况的一种方法是使用 np.ix_
:
>>> a = np.zeros((4,4))
>>> b = np.arange(4).reshape(2,2)+1
>>> ind = [0,3]
>>> np.ix_(ind, ind)
(array([[0],
[3]]), array([[0, 3]]))
>>> a[np.ix_(ind, ind)] += b
>>> a
array([[ 1., 0., 0., 2.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 3., 0., 0., 4.]])
关于python - 如何使用 numpy 在现有 2D 数组中添加 2D 子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21025957/