使用dtype中的重叠字段构造np.array [英] Constructing np.array with overlapping fields in dtype

查看:316
本文介绍了使用dtype中的重叠字段构造np.array的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的dtype如下:

pose_dtype = np.dtype([('x', np.float64), ('y', np.float64), ('theta', np.float64)])

现在,我可以写:

pose = np.array((1, 2, np.pi), dtype=pose_dtype)

我想添加一个xy字段,以使其更易于使用.我可以这样:

I'd like to add an xy field to make this easier to work with. I can do this with:

pose_dtype = np.dtype(dict(
    names=['x', 'y', 'theta', 'xy'],
    formats=[np.float64, np.float64, np.float64, (np.float64, 2)],
    offsets=[0, 8, 16, 0]
))

但是,现在我不再能够使用以前的方法构造数组,而不得不求助于:

However, now I can no longer construct the array using my previous method, and have to resort to:

pose = np.array((1, 2, np.pi, [1, 2]), dtype=pose_dtype)

这是危险的重复.

有什么办法可以将这些属性标记为彼此的别名,这样我就不必对此进行处理了?

Is there any way I can mark the properties as aliases of one another, so that I don't have to deal with this?

推荐答案

按字段而不是按记录填充数组的实验

Experiments in filling an array by field rather than by record

In [207]: pose_dtype = np.dtype(dict(
    names=['x', 'y', 'theta', 'xy'],
    formats=[np.float64, np.float64, np.float64, (np.float64, 2)],
    offsets=[0, 8, 16, 0]
))

In [209]: A=np.zeros((3,),dtype=pose_dtype)
In [210]: A
Out[210]: 
array([(0.0, 0.0, 0.0, [0.0, 0.0]), (0.0, 0.0, 0.0, [0.0, 0.0]),
       (0.0, 0.0, 0.0, [0.0, 0.0])], 
      dtype={'names':['x','y','theta','xy'], 'formats':['<f8','<f8','<f8',('<f8', (2,))], 'offsets':[0,8,16,0], 'itemsize':24})
In [211]: A['x']=[1,2,3]
In [212]: A
Out[212]: 
array([(1.0, 0.0, 0.0, [1.0, 0.0]), (2.0, 0.0, 0.0, [2.0, 0.0]),
       (3.0, 0.0, 0.0, [3.0, 0.0])], 
      dtype={'names':['x','y','theta','xy'], 'formats':['<f8','<f8','<f8',('<f8', (2,))], 'offsets':[0,8,16,0], 'itemsize':24})
In [213]: A['y']=[4,5,6]
In [214]: A
Out[214]: 
array([(1.0, 4.0, 0.0, [1.0, 4.0]), (2.0, 5.0, 0.0, [2.0, 5.0]),
       (3.0, 6.0, 0.0, [3.0, 6.0])], 
      dtype={'names':['x','y','theta','xy'], 'formats':['<f8','<f8','<f8',('<f8', (2,))], 'offsets':[0,8,16,0], 'itemsize':24})
In [215]: A['xy']
Out[215]: 
array([[ 1.,  4.],
       [ 2.,  5.],
       [ 3.,  6.]])
In [216]: A['xy']=np.arange(10,16).reshape(3,2)
In [217]: A
Out[217]: 
array([(10.0, 11.0, 0.0, [10.0, 11.0]), (12.0, 13.0, 0.0, [12.0, 13.0]),
       (14.0, 15.0, 0.0, [14.0, 15.0])], 
      dtype={'names':['x','y','theta','xy'], 'formats':['<f8','<f8','<f8',('<f8', (2,))], 'offsets':[0,8,16,0], 'itemsize':24})

In [219]: A['xy'].dot(A['xy'].T)
Out[219]: 
array([[ 221.,  263.,  305.],
       [ 263.,  313.,  363.],
       [ 305.,  363.,  421.]])

将2个字段作为浮点数组(另一种方法)的另一种方法

another way of getting the 2 fields as a float array (not pretty)

In [228]: A[['x','y']].view(float).reshape(-1,2)
Out[228]: 
array([[ 10.,  11.],
       [ 12.,  13.],
       [ 14.,  15.]])

这篇关于使用dtype中的重叠字段构造np.array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆