gpt4 book ai didi

python - numpy结构化数组上的数组数学

转载 作者:行者123 更新时间:2023-12-04 09:36:42 24 4
gpt4 key购买 nike

import numpy as np
arr = np.array([(1,2), (3,4)], dtype=[('c1', float), ('c2', float)])
arr += 3
导致无效的类型提升错误。有没有办法我可以像结构化数组一样拥有漂亮的标记列,但仍然能够像简单的 dtype=float 那样进行操作大批?
或者,有没有一种简单的方法来转换 dtype=float数组变成结构化数组? IE。
arr = np.array([(1,2), (3,4)], dtype=float)
arr_struc = arr.astype([('c1', float), ('c2', float)])
仅在它不广播并将列与名称匹配的地方。好像我不应该做这个循环:
arr_struc = np.zeros(2, dtype=[('c1', float), ('c2', float)])
for i,key in enumerate(arr_struc.dtype.names): arr_struc[key] = arr[i,:]

最佳答案

嗯。一种选择,为此使用 View :

>>> import numpy as np
>>> arr = np.array([(1,2), (3,4)], dtype=[('c1', float), ('c2', float)])
>>> view = arr.view(float)
>>> view += 3
>>> arr
array([(4., 5.), (6., 7.)], dtype=[('c1', '<f8'), ('c2', '<f8')])
>>> view
array([4., 5., 6., 7.])
不是最干净的。但这是一个解决方案。
编辑:
是的,不要使用 astype再次使用 View :
>>> arr = np.array([(1,2), (3,4)], dtype=float)
>>> arr
array([[1., 2.],
[3., 4.]])
>>> struct = arr.view(dtype=[('c1', float), ('c2', float)])
>>> struct
array([[(1., 2.)],
[(3., 4.)]], dtype=[('c1', '<f8'), ('c2', '<f8')])
>>> struct.shape
(2, 1)
您可能需要根据自己的喜好对其进行 reshape :
>>> struct.squeeze()
array([(1., 2.), (3., 4.)], dtype=[('c1', '<f8'), ('c2', '<f8')])

关于python - numpy结构化数组上的数组数学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62544461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com