[英]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.