如何构建具有 2 个 int 列和 3 个 float 列的 numpy 结构化数组?

How to build a numpy structured array with 2 int columns and 3 float columns?

我有一个 5 元组列表数据。前两个是整数索引 i, j,接下来的三个是浮点数 xyz.

data = [(1, 2, 3.141, 1.414, 2.718), 
        (3, 4, 1.111, 2.222, 3.333),
        (0, 0, 0.000, 0.000, 0.000)]

have heard我可以做类似

的事情
dt    = [('ij', 'int', 2), ('xyz', 'float', 3)]

struct_array = np.array(data, dtype=dt)

所以我可以将数组的最后三列作为二维浮点数组访问。例如得到 r = sqrt(x^2 + y^2 + z^2) 我应该可以说

r = np.sqrt(((struct_array['xyz']**2).sum(axis=1)))

并得到结果

array([4.38780139, 4.15698136, 0.        ])

一样
normal_array = np.array(data)

r = np.sqrt(((array[:, 2:]**2).sum(axis=1)))

但我尝试的所有操作都会导致出现错误消息

ValueError: could not assign tuple of length 5 to structure with 2 fields.

我看过 https://docs.scipy.org/doc/numpy/user/basics.rec.html,但如果我的尝试失败原因的答案在那里,我没有看到它。

对于结构的两个元素,您必须将数据打包到 2 个元组中:

struct_array = np.array([((e[0],e[1]), (e[2],e[3],e[4])) for e in data], dtype=dt)
np.sqrt(((struct_array['xyz']**2).sum(axis=1)))

结果

array([4.38780139, 4.15698136, 0.        ])