gpt4 book ai didi

python - 如何使用 numpy 在现有二维数组中添加二维子数组?

转载 作者:行者123 更新时间:2023-11-28 22:51:57 25 4
gpt4 key购买 nike

我在向现有二维数组添加子数组时遇到问题。我实际上是 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 在现有二维数组中添加二维子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21025957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com