我想附加一些 ndarray 行作為字典的值。但是,我使用 np.vstack 收到了尺寸不等的錯誤。請在這方面指導我。
dic = {0:[],1:[]}
point = np.array([[1,2],
[4,5],
[7,8]])
期望輸出:dic = {0: [[4,5]], 1: [[1,2],[7,8]]}
下面是我試過的代碼:
import numpy as np
dic = {0:[],1:[]}
point = np.array([[1,2],
[4,5],
[7,8]])
dic[0] = np.vstack([dic[1],point[1]])
dic[1] = np.vstack([dic[1],point[0]])
dic[1] = np.vstack([dic[1],point[2]])
錯誤:
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 0 and the array at index 1 has size 3
uj5u.com熱心網友回復:
In [424]: dic = {0:[],1:[]}
...: point = np.array([[1,2],
...: [4,5],
...: [7,8]])
...:
...: dic[0] = np.vstack([dic[1],point[1]])
...: dic[1] = np.vstack([dic[1],point[0]])
...: dic[1] = np.vstack([dic[1],point[2]])
Traceback (most recent call last):
File "<ipython-input-424-e3ba6811826c>", line 6, in <module>
dic[0] = np.vstack([dic[1],point[1]])
File "<__array_function__ internals>", line 5, in vstack
File "/usr/local/lib/python3.8/dist-packages/numpy/core/shape_base.py", line 282, in vstack
return _nx.concatenate(arrs, 0)
File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 0 and the array at index 1 has size 2
看元素np.vstack([dic[1],point[1]])。一個是空串列,另一個是 (2,) 形狀的陣列。 np.array([])是 (0,) 形狀陣列,因此形狀不匹配。 vstack需要將相同大小的陣列放在彼此的頂部。不要假設在處理陣列時空串列的作業方式相同。
In [425]: dic[1]
Out[425]: []
In [426]: point[1]
Out[426]: array([4, 5])
我們可以將初始dic元素定義為 (0,2) 形陣列。然后它們可以與 (2,) 或 (1,2) 陣列甚至 (n,2) 連接。
In [427]: dic = {0:np.zeros((0,2),int), 1:np.zeros((0,2),int)}
In [428]: ...: dic[0] = np.vstack([dic[1],point[1]])
...: ...: dic[1] = np.vstack([dic[1],point[0]])
...: ...: dic[1] = np.vstack([dic[1],point[2]])
...:
In [429]: dic
Out[429]:
{0: array([[4, 5]]),
1: array([[1, 2],
[7, 8]])}
一般來說,迭代連接陣列不是一個好主意;獲得正確的維度很棘手,而且比串列追加要慢。
使用串列追加:
In [432]: dic = {0:[],1:[]}
...: dic[0].append(point[1])
...: dic[1].append(point[0])
...: dic[1].append(point[2])
In [433]: dic
Out[433]: {0: [array([4, 5])], 1: [array([1, 2]), array([7, 8])]}
In [434]: for k,v in dic.items():
...: dic[k]=np.vstack(v)
...:
In [435]: dic
Out[435]:
{0: array([[4, 5]]),
1: array([[1, 2],
[7, 8]])}
uj5u.com熱心網友回復:
不確定您對 的期望vstack,但看起來您正在尋找簡單的切片:
dic[0] = point[[1]]
dic[1] = point[[0,2]]
輸出:
{0: array([[4, 5]]),
1: array([[1, 2],
[7, 8]])}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394732.html
