2016-12-13 114 views
-1

我遇到了numpy,我試圖理解構建multidimensional arrays的正確語法。例如:Python - 多維數組語法

numpy.asarray([[1.,2], [3,4], [5, 6]]) 

打印:

[[ 1. 2.] 
[ 3. 4.] 
[ 5. 6.]] 

而:

numpy.asarray([[1 ,2], [3, 4], [5, 6]]) 

打印:

[[1 2] 
[3 4] 
[5 6]] 

.即是奇數語法元素。

它究竟做了什麼?

+0

設置'dtype'如浮標(用'.')或整數(無'.') –

+0

嗡嗡聲。它可以沿着任何數字,比如'2.'而不是'1.',或'3.','4.'等,並設置'dtype'? –

回答

1

np.array從嵌套的[]dtype推導出元素的形狀與元素的性質。如果至少一個元件是一個Python浮子,整個陣列是浮動:

In [178]: x=np.array([1, 2, 3.0]) # 1d float 
In [179]: x.shape 
Out[179]: (3,) 
In [180]: x.dtype 
Out[180]: dtype('float64') 

如果所有元素都是整數 - 數組也詮釋

In [182]: x=np.array([[1, 2],[3, 4]]) # 2d int 
In [183]: x.shape 
Out[183]: (2, 2) 
In [184]: x.dtype 
Out[184]: dtype('int32') 

也可以設置dtype明確地,例如

In [185]: x=np.array([[1, 2],[3, 4]], dtype=np.float32) 
In [186]: x 
Out[186]: 
array([[ 1., 2.], 
     [ 3., 4.]], dtype=float32) 
In [187]: x.dtype 
Out[187]: dtype('float32')