0
我試圖找出如何空單追加到已經存在的numpy的陣列追加空單numpy.array
我可以得到一個數組的任何名單B
a = np.array([b])
a = np.append(a, [])
print a # you get array([a, []])
這代碼只輸出原始[a]而不是[a,[]]。有誰知道這是如何實現的?
我試圖找出如何空單追加到已經存在的numpy的陣列追加空單numpy.array
我可以得到一個數組的任何名單B
a = np.array([b])
a = np.append(a, [])
print a # you get array([a, []])
這代碼只輸出原始[a]而不是[a,[]]。有誰知道這是如何實現的?
在數組中有一個空列表的唯一方法是創建一個對象dtype數組。
In [382]: a = np.empty((3,),dtype=object)
In [383]: a
Out[383]: array([None, None, None], dtype=object)
In [384]: a[0]=[1,2,3]
In [385]: a[1]=[]
In [386]: a
Out[386]: array([[1, 2, 3], [], None], dtype=object)
或從列表的列表(不同長度的)
In [393]: np.array([[1,2,3],[]])
Out[393]: array([[1, 2, 3], []], dtype=object)
您可以連接一個對象陣列到另一:
In [394]: a = np.empty((1,),object); a[0]=[1,2,3]
In [395]: a
Out[395]: array([[1, 2, 3]], dtype=object)
In [396]: b = np.empty((1,),object); b[0]=[]
In [397]: b
Out[397]: array([[]], dtype=object)
In [398]: np.concatenate((a,b))
Out[398]: array([[1, 2, 3], []], dtype=object)
np.append
包裹concatenate
,並且被設計成添加一個標量到另一個數組。它對一張清單做什麼,空白或其他,是不可預知的。
我把最後一條評論帶回去; np.append
將列表變成一個簡單的數組。這些都做同樣的事情
In [413]: alist=[1,2]
In [414]: np.append(a,alist)
Out[414]: array([[1, 2, 3], 1, 2], dtype=object)
In [415]: np.concatenate((a, np.ravel(alist)))
Out[415]: array([[1, 2, 3], 1, 2], dtype=object)
In [416]: np.concatenate((a, np.array(alist)))
Out[416]: array([[1, 2, 3], 1, 2], dtype=object)
你期望'a.shape'在追加之後? – shx2
這是沒有意義的,你不能改變矩陣的形狀 – ZdaR
a.shape =(2L,)@ shx2 – Glacier11