[英]Update selected columns in 2D numpy array with 1D array
Given the following arrays: 给定以下数组:
from numpy import *
b = ones((5,5))
a = arange(4)
How do I get the following array with minimum amount of code? 如何以最少的代码获取以下数组? Basically update parts of array b
with array a
: 基本上用数组a
更新数组b
部分:
array([[ 1., 0., 0., 0., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 2., 2., 2., 1.],
[ 1., 3., 3., 3., 1.],
[ 1., 1., 1., 1., 1.]])
In matlab I can use one line to achieve this: 在matlab中,我可以使用一行代码来实现这一点:
b = ones(5,5);
a = [0,1,2,3];
b(1:4,2:4) = repmat(a',[1,3])
You can write: 你可以写:
b[0:4, 1:4] = a[:, None]
Which makes b
equal to: 使b
等于:
array([[ 1., 0., 0., 0., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 2., 2., 2., 1.],
[ 1., 3., 3., 3., 1.],
[ 1., 1., 1., 1., 1.]])
b[0:4, 1:4]
selects the appropriate slice of b
(recall that Python uses zero-based indexing). b[0:4, 1:4]
选择适当的b
切片(回想起Python使用从零开始的索引)。
To complete the assignment of the vector a
, it is necessary to add an extra axis of length 1 using a[:, None]
. 为了完成向量a
的分配,必须使用a[:, None]
添加一个长度为1的额外轴。 This is because the slice of b
has shape (4, 3) and we need a
to have shape (4, 1) so that the axes line up correctly to allow broadcasting. 这是因为b
的切片的形状为(4,3),我们需要a
形状为(4,1),以便轴正确对齐以允许广播。
Initialize output array and set a
, just like we did for MATLAB - 初始化输出数组并设置a
,就像我们对MATLAB所做的那样-
b = np.ones((5,5))
a = np.array([0,1,2,3])
Now, let's use the automatic broadcasting supported by NumPy to replace the explicit replication done by repmat
in MATLAB, for which we need to make a
a 2D array by "pushing" the 1D elements along the first axis and introducing a singleton dimension as the second axis with np.newaxis
as a[:,np.newaxis]
. 现在,让我们使用由NumPy的支持自动播放,以取代被做了明确的复制repmat
在MATLAB,为此,我们需要a
由“推”沿第一轴的一维元素,并引入一个单维度的第二二维数组np.newaxis
为a[:,np.newaxis]
轴。 Please note the general term for dimension in NumPy is axis. 请注意,NumPy中尺寸的通用术语是轴。 A shorthand for np.newaxis
is None
, thus we need to use a[:,None]
and use this for assigning elements into b
. np.newaxis
的简写是None
,因此我们需要使用a[:,None]
并将其分配给b
。
Thus, the final step would be considering we have 0-based
indexing in Python, we would have - 因此,最后一步将是考虑在Python中0-based
索引,我们将-
b[0:4,1:4] = a[:,None]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.