numpy结构化数组添加记录 [英] numpy Structured array adding record
问题描述
我有一个像这样的结构化数组:
I have an Structured array like this:
a = np.array([(0. , 1. , 2.) , (10. , 11. , 12. )] ,
dtype=[('PositionX', '<f8'), ('PositionY', '<f8'), ('PositionZ', '<f8')])
现在,我想添加记录0(a [0])和记录1(a [1]),以获得类似以下内容: (10.,12,14.)
Now, I want add record 0 (a[0]) and record 1 (a[1]), to get something like : (10. , 12. , 14. )
当我写类似的东西时:
a[0] + a[1]
我收到一个错误消息,告诉我您不能添加两个dtype对象或类似的东西.
I got error which tell me you cant add two dtype object or something like that.
因此,我想也许我可以将[0]设为常规向量,然后执行加法运算.
So, I think maybe I can turn a[0] to be a regular vector, then perform adding.
但是numpy.array(a [0])具有与a [0]相同的dtype,并且numpy.array(a[0],dtype=np.float64)
也不起作用.
But numpy.array(a[0]) have same dtype as a[0], and numpy.array(a[0],dtype=np.float64)
does not work too.
那么,谁能告诉我如何将a [0]转换为常规向量?请不要告诉我将结构化数组转换为常规数组.因为我只想提取阵列记录中的一部分并添加. 此外,我真的很想知道如何将像a [0]这样的对象转换为常规向量.
So, can anyone tell me how to convert a[0] to regular vector? please don't tell me to covert structured array to regular array. because I just want take few of my array record and do adding. Besides, I really want to know how to turn an object like a[0] to an regular vector.
推荐答案
仅仅因为a [i]是元组,您会收到一个错误,您不能直接添加元组.您必须访问它们,实现这一目标的更Python方式是:
You're getting an error just because the a[i] are tuples, you can't add directly tuple. You have to access them, a more pythonic way to achieve this would be:
map(sum, zip(*a))
zip函数可以完全满足您的需求,之后您必须根据需要处理每个条目,在您使用sum
的情况下,您还可以尝试以下操作:
the zip function do exactly what you're looking for, after that you have to process each entry according to what you need, in your case sum
, you can also try this:
result = []
for elem in zip(*a):
result.append(sum(elem))
这篇关于numpy结构化数组添加记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!