分配给NumPy中的列?
问题描述:
如何使用NumPy编写以下MATLAB代码?
How could the following MATLAB code be written using NumPy?
A = zeros(5, 100);
x = ones(5,1);
A(:,1) = x;
分配行似乎很容易,但是我找不到将数组分配给另一个数组的列的示例.
Assigning to rows seems to work easily, but I couldn't find an example of assigning an array to a column of another array.
答
使用a[:,1] = x[:,0]
.您需要x[:,0]
来选择x
的列作为单个numpy数组.如果您可以选择x
的格式,最好不要首先使其成为二维数组,而要使其成为常规的(行)数组:
Use a[:,1] = x[:,0]
. You need x[:,0]
to select the column of x
as a single numpy array. If you have the choice of how to format x
, it's better to not make it a 2-dimensional array in the first place, but just a regular (row) array:
>>> a
array([[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.],
[ 0., 0., 0.]])
>>> x = numpy.ones(5)
>>> x
array([ 1., 1., 1., 1., 1.])
>>> a[:,1] = x
>>> a
array([[ 0., 1., 0.],
[ 0., 1., 0.],
[ 0., 1., 0.],
[ 0., 1., 0.],
[ 0., 1., 0.]])