python - 引用numpy结构化数组中的字段与整个数组的大小相同

标签 python numpy structured-array

问题

我有一个 numpy 结构化数组,我想获取两个小字段。当我这样做时,我得到了一个和原来一样大的项目

示例

>>> A = np.zeros(100, dtype=[('f',float),('x',float,2),('large',float,500000)])
>>> A.itemsize
4000024
>>> A['f'].itemsize
8
>>> A['x'].itemsize
8
>>> A[['x','f']].itemsize
4000024
>>> A[['x']].itemsize
4000024

问题

为什么在 numpy 数组中提取字段切片会产生与原始数组一样大的数组? (我使用的是python3.8和numpy版本1.18.3)

最佳答案

制作一个足够小以实际显示的数组:

In [151]: A = np.zeros(3, dtype=[('f',float),('x',float,2),('large',float,10)])
In [152]: A
Out[152]: 
array([(0., [0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
       (0., [0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
       (0., [0., 0.], [0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])],
      dtype=[('f', '<f8'), ('x', '<f8', (2,)), ('large', '<f8', (10,))])

选择一个字段:

In [153]: A['f']
Out[153]: array([0., 0., 0.])

选择字段列表:

In [154]: A[['f']]
Out[154]: 
array([(0.,), (0.,), (0.,)],
      dtype={'names':['f'], 'formats':['<f8'], 'offsets':[0], 'itemsize':104})

从版本 1.17 开始,使用字段列表进行索引会返回一个 View 。因此 itemsize 与原始的相同。

In [155]: A.itemsize
Out[155]: 104
In [156]: A[['x']].itemsize
Out[156]: 104

查看最后一个字段时,列表索引与字段名称索引之间的区别可能会更清楚。一个仍然是结构化数组,另一个是二维数组。

In [159]: A[['large']].dtype
Out[159]: dtype({'names':['large'], 'formats':[('<f8', (10,))], 'offsets':[24], 'itemsize':104})

In [160]: A[['large']].shape
Out[160]: (3,)
In [161]: A['large'].shape
Out[161]: (3, 10)

https://numpy.org/doc/stable/user/basics.rec.html#accessing-multiple-fields

Note that unlike for single-field indexing, the dtype of the view has the same itemsize as the original array, and has fields at the same offsets as in the original array, and unindexed fields are merely missing.

关于python - 引用numpy结构化数组中的字段与整个数组的大小相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64035390/

相关文章:

python - 如何以编程方式在python中为caffe生成deploy.txt

python - 向量化python函数

python父类 'wrapping'子类方法

jupyter中的Python Import cv2错误适用于mac终端

python - Numpy reshape 对复制数组和未复制数组的作用不同

python - 用 numpy 和测试套件打包

python - 如何使用结构化数据填充多个命名字段

python - 添加和访问 numpy 结构化数组的对象类型字段

python - numpy fromfile 和结构化数组

python - 如何用Signal控制QProgressBar