python - 使用结构化数组来命名 numpy 数组中的轴

标签 python arrays numpy structured-array

我一定犯了某种非常微不足道的错误,但我正在尝试创建一个具有单轴名称的结构化数组,例如,我有一个形状为 的数组 data (2, 3, 4),我想命名第一个轴,以便我可以访问 data['a']data['b'] 在这两种情况下都会得到 (3, 4) 形状的切片。我尝试过:

shape = (2, 3, 4)
data = np.arange(np.product(shape)).reshape(shape)

dtype = [(nn, float) for nn in ['a', 'b']]
data = np.array(data, dtype=dtype)

但这似乎将所有数据复制到“a”和“b”中,例如

print(data.shape)
print(data['a'].shape)
> (2, 3, 4)
> (2, 3, 4)

我尝试指定形状(在 dtype 规范中)应为 (3, 4),但这又将数据重复了 12 次...并且我尝试将轴顺序更改为 >(3, 4, 2),但这没有任何作用。任何帮助表示赞赏!

最佳答案

In [263]: shape = (2, 3, 4)
     ...: data = np.arange(np.product(shape)).reshape(shape)
     ...: 
     ...: dtype = [(nn, float) for nn in ['a', 'b']]

虽然可以转换数据,但更可靠的方法是创建所需的目标数组,并将值复制到其中:

In [264]: res = np.zeros(shape[1:], dtype)
In [265]: res['a'] = data[0]
In [266]: res['b'] = data[1]
In [267]: res
Out[267]: 
array([[( 0., 12.), ( 1., 13.), ( 2., 14.), ( 3., 15.)],
       [( 4., 16.), ( 5., 17.), ( 6., 18.), ( 7., 19.)],
       [( 8., 20.), ( 9., 21.), (10., 22.), (11., 23.)]],
      dtype=[('a', '<f8'), ('b', '<f8')])
In [268]: res['a'].shape
Out[268]: (3, 4)

在此结构化数组中,一条记录由 2 个 float 和数据缓冲区组成,包含:

In [272]: res.view(float).ravel()
Out[272]: 
array([ 0., 12.,  1., 13.,  2., 14.,  3., 15.,  4., 16.,  5., 17.,  6.,
       18.,  7., 19.,  8., 20.,  9., 21., 10., 22., 11., 23.])

这与数据[0,1,2,3,...]不同。因此,没有任何形式的 reshape 、 View 或类型可以将一种类型转换为另一种类型。

因此有一个从结构化数组到 (3,4,2) 数组的简单映射,但不是您的源。

In [273]: res.view(float).reshape(3,4,2)
Out[273]: 
array([[[ 0., 12.],
        [ 1., 13.],
        [ 2., 14.],
        [ 3., 15.]],

       [[ 4., 16.],
        [ 5., 17.],
        [ 6., 18.],
        [ 7., 19.]],

       [[ 8., 20.],
        [ 9., 21.],
        [10., 22.],
        [11., 23.]]])

关于python - 使用结构化数组来命名 numpy 数组中的轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54407313/

相关文章:

python - Osmnx 和 basemap

python - 实现 css 解析器/替换器的 pythonic 方法是什么

javascript - 最小最大值二维数组javascript

c# - double 数组

python - 使用 argsort 进行 Numpy 索引

python - 无法使用 python 脚本更改 docker 容器内的工作目录

python key 错误 : 'sapi5'

c - 嵌套 for 循环改进

python - Python 中的向量化字典

python - 将 x,y 坐标放入 bin 中