[英]Adding elements to numpy array
使用 NumPy:
X= numpy.zeros(shape=[1, 4], dtype=np.int)
如何添加列表,例如[1,2,3,4]
? 我試過numpy.add(X,[1,2,3,4])
和np.hstack((1,2,3,4))
但它們都不起作用!
我知道如何使用append
方法在標准 Python 列表中使用它,但我想使用 numpy 來提高性能。
Numpy 數組在創建后不會改變形狀。 因此,在調用方法zeros((1,4), ...)
,您已經擁有一個充滿零的 1x4 矩陣。 要將其元素設置為非零值,您需要使用賦值運算符:
X[0] = [1, 2, 3, 4] # does what you are trying to achieve in your question
X[0, :] = [1, 2, 3, 4] # equivalent to the above
X[:] = [1, 2, 3, 4] # same
X[0, 1] = 2 # set the individual element at [0, 1] to 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.