You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在NumPy 1.14中如何将结构化数组切片转换为常规NumPy数组

Got it, let's fix this issue specifically for NumPy 1.14. The problem with your original code is that arr2[0] gives you a 0-dimensional structured scalar, and in NumPy 1.14, you can't directly use view() on a 0d scalar to reshape it into a 2-element float32 array—hence that ValueError.

Here are two reliable solutions that work perfectly with NumPy 1.14:

Solution 1: Use view() on the entire sliced array (not the single element)

Instead of accessing the 0th element first, apply view() directly to arr2 (which is a 1-dimensional structured array). This works because the array has an explicit axis that NumPy can map to the new dtype structure:

import numpy as np

arr = np.array([(105.0, 34.0, 145.0, 217.0)], dtype=[('a', 'f4'), ('b', 'f4'), ('c', 'f4'), ('d', 'f4')])
arr2 = arr[['a', 'b']]
out = arr2.view((np.float32, 2))
# Result: array([[105.,  34.]], dtype=float32)

Solution 2: Stack field arrays explicitly (more readable)

If you prefer a more intuitive approach that avoids relying on memory layout details, you can stack the individual field arrays along the second axis. This method is also fully compatible with NumPy 1.14:

import numpy as np

arr = np.array([(105.0, 34.0, 145.0, 217.0)], dtype=[('a', 'f4'), ('b', 'f4'), ('c', 'f4'), ('d', 'f4')])
arr2 = arr[['a', 'b']]
out = np.stack([arr2['a'], arr2['b']], axis=1)
# Result: array([[105.,  34.]], dtype=float32)

Both approaches will give you the regular 2D float32 array you need without triggering that error. The first method is more efficient (it’s just a memory view with no data copying), while the second is easier to read if you want to avoid low-level dtype mapping logic.

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:28:51