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

标签 python arrays numpy

我在向现有二维数组添加子数组时遇到问题。 我实际上是 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/

相关文章:

Python - 程序收到信号 SIGSEGV,段错误

python - 如何在pygame中的while循环中更改/获取矩形的值

python - 传递数学方程作为参数(numpy)

ruby - 按键对哈希数组进行分组

python - 准备张量分配时出现意外失败 : tensorflow/lite/kernels/reshape. cc :85 num_input_elements ! = num_output_elements (1200 != 0)

python - pandas Series.tolist() 中的 NaN 与 list 中的 NaN 的行为不同

Python函数调用顺序

python - 去除 Python 2.x 中的特定标点符号

c++ - 如何从最大到最小组织一个数组中的前10个频繁值?

java - 为什么我的代码修改了错误的数组?