![](/img/trans.png)
[英]ValueError: could not broadcast input array from shape (22500,3) into shape (1)
[英]ValueError: could not broadcast input array from shape (3) into shape (2) simple solution
我有這個 np 數組,並嘗試在其中一行中添加一個數字(如果可能,嘗試創建非對稱數組,如果不是 100*3 數組也可以)
a=np.arange(100*2).reshape(-1,2)
a[40]=np.append(a[40],6)
請注意, a=np.arange(100*2).reshape(-1,2)
只是簡化示例,而不是我想要操作的真實代碼。 我收到這個錯誤
ValueError: could not broadcast input array from shape (3) into shape (2)
有沒有簡單的解決方案(除了創建新數組並用先前值循環填充然后添加 6)?
這能解決你的問題嗎?
import numpy as np
a = np.zeros((100, 3))
a[:,0:2] = np.arange(100*2).reshape(-1,2)
a[40,2]=6
numpy
最接近numpy
的數組的是對象 dtype 數組:
In [475]: a = np.empty(2, object)
In [476]: a
Out[476]: array([None, None], dtype=object)
如果一個元素是一個列表,你可以使用它的append
添加一個值:
In [477]: a[0] = [1,2]
In [478]: a[1] = [2,3]
In [479]: a[1].append(4)
In [480]: a
Out[480]: array([list([1, 2]), list([2, 3, 4])], dtype=object)
但是這樣的數組是否比列表更好是值得懷疑的
In [481]: a.tolist()
Out[481]: [[1, 2], [2, 3, 4]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.