如何获取结构化numpy数组的和?

wsewodh2  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(65)

我试图得到一个结构化数组的和。是否需要在字段名称周围使用“for”循环,或者我可以在一行中完成。我每次跑步都要这样做一百万次,所以我需要保持快速。

>>> test = np.array([(1,2,3),(4,5,6)], dtype={'names' : ["One", "Two", "Three"], 'formats' : ["f8"]*3})
>>> test
array([(1., 2., 3.), (4., 5., 6.)],
      dtype=[('One', '<f8'), ('Two', '<f8'), ('Three', '<f8')])
>>> np.sum(test)
...
numpy.core._exceptions._UFuncNoLoopError: ufunc 'add' did not contain a loop with signature matching types (dtype([('One', '<f8'), ('Two', '<f8'), ('Three', '<f8')]), dtype([('One', '<f8'), ('Two', '<f8'), ('Three', '<f8')])) -> None

字符串
与np.sum(test,axis=0)相似
我期待一个结构化数组:[(5,7,9),dtype=...]。至少,没有错误。

gojuced7

gojuced71#

因此,在这种情况下,由于您的结构具有相同的基本类型,因此您可以很容易地使用视图:

>>> import numpy as np
>>> test = np.array([(1,2,3),(4,5,6)], dtype={'names' : ["One", "Two", "Three"], 'formats' : ["f8"]*3})
>>> test.view('f8').reshape(-1,3).sum(axis=0)
array([5., 7., 9.])

字符串
现在,如果你不能很容易地从你原来的结构化dtype创建一个视图,你可以使用一个字段循环,这应该不会太慢:

>>> result = np.zeros_like(test, shape=(1,))
>>> for field in test.dtype.fields:
...     result[field] = test[field].sum()
...
>>> result
array([(5., 7., 9.)],
      dtype=[('One', '<f8'), ('Two', '<f8'), ('Three', '<f8')])

相关问题