Numpy Python-多维数组语法

Numpy Python-多维数组语法,numpy,multidimensional-array,Numpy,Multidimensional Array,我遇到了numpy,正在试图理解构建多维数组的正确语法。例如: numpy.asarray([[1.,2], [3,4], [5, 6]]) 印刷品: [[ 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.]] [[1 2] [3 4] [5 6]] 那是一个奇怪的语

我遇到了
numpy
,正在试图理解构建
多维数组的正确语法。例如:

numpy.asarray([[1.,2], [3,4], [5, 6]])
印刷品:

[[ 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.]]
[[1 2]
 [3 4]
 [5 6]]
那是一个奇怪的语法元素


它到底在做什么?

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')
如果所有元素都是整数-则数组也为int

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')

dtype
设置为float(带
)或int(不带
)hum。它可以使用任何数字,比如
2.
而不是
1.
,或者
3.
4.
等等,并设置
数据类型