[英]Numpy How to assign values of a column of a matrix with another vector?
I'm trying to make an empty 3x2 matrix, then replace each column into randomly generated vectors.我正在尝试制作一个空的 3x2 矩阵,然后将每一列替换为随机生成的向量。
Therefore, I tried to run the following code:因此,我尝试运行以下代码:
import numpy as np
A = np.empty(shape=(3,2))
x1 = np.random.rand(3,1)
x2 = np.random.rand(3,1)
A[:,1] = x1
A[:,2] = x2
However, when I tried to run the code, I got the following error message:但是,当我尝试运行代码时,我收到以下错误消息:
A[:,1] = x1
ValueError: could not broadcast input array from shape (3,1) into shape (3)
How can I fix the error?如何修复错误?
Thank you.谢谢你。
There are several things wrong here.这里有几件事是错误的。 First you're trying to assign to a slice a higher dimensional array:首先,您尝试为切片分配更高维的数组:
A[:,0].shape
# (3,)
x1.shape
#(3, 1)
On another side, you're wrongly indexing, indices in numpy (and python more generally) begin at position 0
.另一方面,您错误地索引, numpy (以及更一般的 python )中的索引从 position 0
开始。 So taking these aspects into consideration, you could either assign as:因此,考虑到这些方面,您可以指定为:
A = np.empty(shape=(3,2))
x1 = np.random.rand(3,1)
x2 = np.random.rand(3,1)
A[:,0] = x1.ravel()
A[:,1] = x2.ravel()
A
array([[0.2331048 , 0.2974727 ],
[0.6789782 , 0.9680256 ],
[0.0151457 , 0.05476883]])
Or note that np.random.rand
can generate arrays of multiple dimensions:或者注意np.random.rand
可以生成多个维度的arrays:
np.random.rand(3,2)
array([[0.10108146, 0.14859229],
[0.55174044, 0.7399697 ],
[0.38104021, 0.32287851]])
A
is of size 3 X 2
ie it has 3
rows and 2
columns A
的大小为3 X 2
,即它有3
行和2
列A[:,1]
implies all rows of A
and second column. A[:,1]
表示A
所有行和第二列。 Array are 0 indexed in python数组在 python 中索引为 0A[:,1]
is a column vector so you can assign any vector of size 3 into it A[:,1]
是一个列向量,因此您可以将任何大小为 3 的向量分配给它np.random.rand(3,1)
returns a numpy array (matrix) or size 3 X 1
. np.random.rand(3,1)
返回一个 numpy 数组(矩阵)或大小3 X 1
。 But what you want is a vector ie np.random.rand(3)
但是你想要的是一个向量,即np.random.rand(3)
A = np.empty(shape=(3,2))
x1 = np.random.rand(3)
x2 = np.random.rand(3)
A[:,0] = x1
A[:,1] = x2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.