分配给NumPy中的列? [英] Assigning to columns in NumPy?
本文介绍了分配给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.]])
这篇关于分配给NumPy中的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文