我需要一个表达式来授予我一个 8 元组 float
数组。目前,我有 8 元组数组:
E = np.zeros((n,m), dtype='8i') #8-tuple
但是,当我通过以下方式附加索引 i,j
时:
E[i,j][0] = 1000.2 #etc.
我得到一个数据类型为 int
的元组数组:
[1000 0 0 0 0 0 0 0]
看来我需要一种在我的 zeros
命令中使用 dtype
的方法来设置 n 元组和 float
值。有谁知道这是怎么做到的?
最佳答案
如果数组是整数 dtype
,则分配的值将被截断:
In [169]: x=np.array([0,1,2])
In [170]: x
Out[170]: array([0, 1, 2])
In [173]: x[0] = 1.234
In [174]: x
Out[174]: array([1, 1, 2])
数组必须有一个 float 据类型来保存浮点值。
只需将 i
(整数)更改为 f
( float )即可生成 float 组:
In [166]: E = np.zeros((2,3), dtype='8f')
In [167]: E.shape
Out[167]: (2, 3, 8)
In [168]: E.dtype
Out[168]: dtype('float32')
这个 '8f' 数据类型并不常见。该字符串实际上转换为:
In [175]: np.dtype('8f')
Out[175]: dtype(('<f4', (8,)))
但是当在 np.zeros
中使用时,8
被视为一个维度。通常我们指定形状中的所有尺寸,如@FHTMitchell 所述:
In [176]: E1 = np.zeros((2,3,8), dtype=np.float32)
In [177]: E1.shape
Out[177]: (2, 3, 8)
In [178]: E1.dtype
Out[178]: dtype('float32')
您对“n 元组”的使用不清楚。虽然 shape
是一个元组,但数值数组不使用元组表示法。这是为结构化数组保留的。
In [180]: np.zeros((3,), dtype='f,f,f,f')
Out[180]:
array([(0., 0., 0., 0.), (0., 0., 0., 0.), (0., 0., 0., 0.)],
dtype=[('f0', '<f4'), ('f1', '<f4'), ('f2', '<f4'), ('f3', '<f4')])
In [181]: _.shape
Out[181]: (3,)
这是一个包含 3 个元素的一维数组。 dtype
显示 4 个字段。每个元素或记录都显示为一个元组。
但是字段是按名称而不是数字索引的:
In [182]: Out[180]['f1']
Out[182]: array([0., 0., 0.], dtype=float32)
也可以在字段中放置“数组”:
In [183]: np.zeros((3,), dtype=[('f0','f',(4,))])
Out[183]:
array([([0., 0., 0., 0.],), ([0., 0., 0., 0.],), ([0., 0., 0., 0.],)],
dtype=[('f0', '<f4', (4,))])
In [184]: _['f0']
Out[184]:
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]], dtype=float32)
最初我认为 8f
符号会产生这种数组。但显然我必须要么使用带有字段名称的完整符号,要么制作一个逗号分隔的字符串:
In [185]: np.zeros((3,), dtype='4f,i')
Out[185]:
array([([0., 0., 0., 0.], 0), ([0., 0., 0., 0.], 0),
([0., 0., 0., 0.], 0)], dtype=[('f0', '<f4', (4,)), ('f1', '<i4')])
dtype
符号可能会造成混淆,https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.dtypes.html
除非您有意尝试创建结构化数组,否则最好远离“8f”符号。
In [189]: np.array([0,1,2,3],dtype='4i')
TypeError: object of type 'int' has no len()
In [190]: np.array([[0,1,2,3]],dtype='4i')
TypeError: object of type 'int' has no len()
In [191]: np.array([(0,1,2,3)],dtype='4i') # requires [(...)]
Out[191]: array([[0, 1, 2, 3]], dtype=int32)
没有 4,我可以简单地写:
In [193]: np.array([[0,1,2,3]], dtype='i')
Out[193]: array([[0, 1, 2, 3]], dtype=int32)
In [194]: np.array([0,1,2,3], dtype='i')
Out[194]: array([0, 1, 2, 3], dtype=int32)
In [195]: np.array([[0,1,2,3]])
Out[195]: array([[0, 1, 2, 3]])
关于python - 具有 dtype float 的 Numpy n 元组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48402274/