2013-10-22 34 views
0

與NumPy陣列之間有什麼區別:關於在Python

import numpy as np 
A = np.zeros((3,)) 

import numpy as np 
B = np.zeros((1,3)) 

謝謝您的回答!

+2

看看'A.shape'和'B.shape' – tacaswell

+0

第二個有語法錯誤... – mguijarr

+0

tcaswell:你能解釋給我嗎? A.shape =(3,)和B.shape =(1,3) – user2863620

回答

2

希望這些說明在實踐中的差異。

>>> A = np.zeros((3,)) 
>>> B = np.zeros((1,3)) 
>>> A #no column, just 1D 
array([ 0., 0., 0.]) 
>>> B #has one column 
array([[ 0., 0., 0.]]) 
>>> A.shape 
(3,) 
>>> B.shape 
(1, 3) 
>>> A[1] 
0.0 
>>> B[1] #can't do this, it will take the 2nd column, but there is only one column. 

Traceback (most recent call last): 
    File "<pyshell#89>", line 1, in <module> 
    B[1] 
IndexError: index 1 is out of bounds for axis 0 with size 1 
>>> B[0] #But you can take the 1st column 
array([ 0., 0., 0.]) 
>>> B[:,1] #take the 2nd cell, for each column 
array([ 0.]) 
>>> B[0,1] #how to get the same result as A[1]? take the 2nd cell of the 1st col. 
0.0 
2

第一個產生的零的1D numpy.array

>>> import numpy as np 
>>> A = np.zeros((3,)) 
>>> A 
array([ 0., 0., 0.]) 
>>> A[0] 
0.0 
>>> 

第二創建2D 1行和3列的numpy.array,用零填充:

>>> import numpy as np 
>>> B = np.zeros((1,3)) 
>>> B 
array([[ 0., 0., 0.]]) 
>>> B[0] 
array([ 0., 0., 0.]) 
>>> 

這裏是如果您需要更多詳細信息,請參閱numpy.zerosnumpy.array

+1

B不是嵌套數組,它是2維數組。它們不是同一件事。 – Evan

+0

不,它不...''np.zeros((1,3))'創建一個1行3列的二維數組,填充零。 「數組內的數組」可能是一個有用的隱喻,但它對numpy處理數組和內存的描述很差。 – Jaime

+0

好的。我試圖保持簡單,因爲OP顯然是NumPy的新手。但是,我想最好是技術。 – iCodez

1

A是一個具有三個元素的一維數組。

B是具有一行三列的二維陣列。

您也可以使用C = np.zeros((3,1))這將創建一個三行和一列的二維數組。

A,B和C具有相同的元素 - 不同之處在於它們將如何被稍後調用解釋。例如,某些numpy調用可以在特定的維度上運行,或者可以被告知在特定的維度上運行。例如總和:

>> np.sum(A, 0) 
    3.0 
>> np.sum(B, 0) 
    array([ 1., 1., 1.]) 

他們也有不同的行爲與基體/張量操作,如dot,並且也喜歡hstackvstack操作。

如果你打算使用的是矢量,表單A通常會做你想要的。額外的「單身」維度(即尺寸爲1的維度)只是您必須追蹤的額外信息。但是,如果您需要與二維數組交互,則可能需要區分行向量和列向量。在這種情況下,表格B和C將會很有用。