我有一个由函数返回的recarray,我想将它转换为具有相同dtype的ndarray。下面的代码中的z变量就是一个例子。我怎样才能得到d1从dtype of z
>>> d1 = np.dtype([('a', float), ('b', int)])
>>> x = np.random.randn(4).view(d1); x
array([( 1.3209, -1.11 ), (-1.1721, -0.5442)],
dtype=[('a', '<f8'), ('b', '<f8')])
>>> y = x.view(np.recarray); y
rec.array([( 1.3209, -1.11 ), (-1.1721, -0.5442)],
dtype=[('a', '<f8'), ('b', '<f8')])
>>> z = y.view(np.ndarray); z
array([( 1.3209, -1.11 ), (-1.1721, -0.5442)],
dtype=(numpy.record, [('a', '<f8'), ('b', '<f8')]))现在,您可以看到z和x具有相同的数据结构,但具有不同的dtype。z.dtype在x.dtype上有一个包装器np.record。如何删除包装器以获取底层d1
发布于 2019-03-22 17:22:34
In [19]: d1 = np.dtype([('a',float),('b',float)]) 结构化数组
In [20]: x = np.array([(1,2),(3,4),(5,6)], d1)
In [21]: x
Out[21]: array([(1., 2.), (3., 4.), (5., 6.)], dtype=[('a', '<f8'), ('b', '<f8')])重新排列的视图:
In [22]: y = x.view(np.recarray)
In [23]: y
Out[23]:
rec.array([(1., 2.), (3., 4.), (5., 6.)],
dtype=[('a', '<f8'), ('b', '<f8')])The dtype
In [24]: x.dtype
Out[24]: dtype([('a', '<f8'), ('b', '<f8')])
In [25]: y.dtype
Out[25]: dtype((numpy.record, [('a', '<f8'), ('b', '<f8')]))dtype descr匹配,所以我们可以:
In [26]: y.dtype.descr
Out[26]: [('a', '<f8'), ('b', '<f8')]
In [27]: np.dtype(y.dtype.descr)
Out[27]: dtype([('a', '<f8'), ('b', '<f8')])
In [28]: x.dtype
Out[28]: dtype([('a', '<f8'), ('b', '<f8')])https://docs.scipy.org/doc/numpy/user/basics.rec.html#record-arrays
为了方便起见,将ndarray视为np.recarray类型将自动转换为np.record数据类型,因此可以将dtype排除在视图之外: 要返回到普通的ndarray,必须重置dtype和type。考虑到记录不是结构化类型这一不寻常的情况,以下观点是这样做的:
In [31]: y.view(y.dtype.fields, np.ndarray)
Out[31]: array([(1., 2.), (3., 4.), (5., 6.)], dtype=[('a', '<f8'), ('b', '<f8')])===
随着多字段访问方式的改变,recfunctions添加了一些实用函数。一个人将结构化转换为非结构化(在过去一直有点尴尬):
In [35]: import numpy.lib.recfunctions as rf
In [36]: rf.structured_to_unstructured(x)
Out[36]:
array([[1., 2.],
[3., 4.],
[5., 6.]])
In [37]: rf.structured_to_unstructured(y)
Out[37]:
rec.array([[1., 2.],
[3., 4.],
[5., 6.]],
dtype=float64)
In [38]: rf.structured_to_unstructured(y).view(np.ndarray)
Out[38]:
array([[1., 2.],
[3., 4.],
[5., 6.]])另一个方向是:
In [39]: rf.unstructured_to_structured(Out[36], x.dtype)
Out[39]: array([(1., 2.), (3., 4.), (5., 6.)], dtype=[('a', '<f8'), ('b', '<f8')])https://stackoverflow.com/questions/55293809
复制相似问题