2016-12-13 64 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')