Python - 多维数组语法
问题描述:
我遇到了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]]
.
即是奇数语法元素。
它究竟做了什么?
答
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')
设置'dtype'如浮标(用'.')或整数(无'.') –
嗡嗡声。它可以沿着任何数字,比如'2.'而不是'1.',或'3.','4.'等,并设置'dtype'? –