[英]How to assign a (row) numpy.matrix to a column in a numpy.matrix
[英]Numpy How to assign values of a column of a matrix with another vector?
我正在尝试制作一个空的 3x2 矩阵,然后将每一列替换为随机生成的向量。
因此,我尝试运行以下代码:
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
但是,当我尝试运行代码时,我收到以下错误消息:
A[:,1] = x1
ValueError: could not broadcast input array from shape (3,1) into shape (3)
如何修复错误?
谢谢你。
这里有几件事是错误的。 首先,您尝试为切片分配更高维的数组:
A[:,0].shape
# (3,)
x1.shape
#(3, 1)
另一方面,您错误地索引, numpy (以及更一般的 python )中的索引从 position 0
开始。 因此,考虑到这些方面,您可以指定为:
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]])
或者注意np.random.rand
可以生成多个维度的arrays:
np.random.rand(3,2)
array([[0.10108146, 0.14859229],
[0.55174044, 0.7399697 ],
[0.38104021, 0.32287851]])
A
的大小为3 X 2
,即它有3
行和2
列A[:,1]
表示A
所有行和第二列。 数组在 python 中索引为 0A[:,1]
是一个列向量,因此您可以将任何大小为 3 的向量分配给它np.random.rand(3,1)
返回一个 numpy 数组(矩阵)或大小3 X 1
。 但是你想要的是一个向量,即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.