且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

记录 numpy astype 的奇怪行为

更新时间:2023-02-27 13:11:58

https://docs.scipy.org/doc/numpy/user/basics.rec.html#assignment-from-other-structured-arrays

表示来自其他结构化数组的分配是按位置,而不是按字段名称.我认为这适用于 astype.如果是这样,则意味着您无法使用 astype 重新排序字段.

says that assignment from other structured arrays is by position, not by field name. I think that applies to astype. If so it means you can't reorder fields with an astype.

一次访问多个字段在最近的版本中发生了变化,并且可能会发生更多变化.部分原因在于此类访问应该是副本还是视图.

Accessing multiple fields at once has changed in recent releases, and may change more. Part of it is whether such access should be a copy or view.

recfunctions 具有用于添加、删除或合并字段的代码.一个常见的策略是使用新的 dtype 创建一个目标数组,并按字段名称将值复制到它.这是迭代的,但由于通常数组的记录比字段多得多,因此时间损失不大,

recfunctions has code for adding, deleting or merging fields. A common strategy is to create a target array with the new dtype, and copy values to it by field name. This is iterative but since typically an array will have many more records than fields the time penalty isn't big,

在 1.14 版本中,我可以:

In version 1.14, I can do:

In [152]: dt1 = np.dtype([('a',float),('b',int), ('c','U3')])
In [153]: dt2 = np.dtype([('b',int),('a',float), ('c','S3')])

In [154]: arr1 = np.array([(1,2,'a'),(3,4,'b'),(5,6,'c')], dt1)
In [155]: arr1
Out[155]: 
array([(1., 2, 'a'), (3., 4, 'b'), (5., 6, 'c')],
      dtype=[('a', '<f8'), ('b', '<i8'), ('c', '<U3')])

仅使用 astype 不会对字段重新排序:

Simply using astype does not reorder the fields:

In [156]: arr1.astype(dt2)
Out[156]: 
array([(1, 2., b'a'), (3, 4., b'b'), (5, 6., b'c')],
      dtype=[('b', '<i8'), ('a', '<f8'), ('c', 'S3')])

但多字段索引确实:

In [157]: arr1[['b','a','c']]
Out[157]: 
array([(2, 1., 'a'), (4, 3., 'b'), (6, 5., 'c')],
      dtype=[('b', '<i8'), ('a', '<f8'), ('c', '<U3')])

现在 dt2 astype 是正确的:

now the dt2 astype is right:

In [158]: arr2 = arr1[['b','a','c']].astype(dt2)

In [159]: arr2
Out[159]: 
array([(2, 1., b'a'), (4, 3., b'b'), (6, 5., b'c')],
      dtype=[('b', '<i8'), ('a', '<f8'), ('c', 'S3')])

In [160]: arr1['a']
Out[160]: array([1., 3., 5.])

In [161]: arr2['a']
Out[161]: array([1., 3., 5.])

这是 1.14;您使用的是 1.15,并且文档中提到了 1.16 中的差异.所以这是一个移动的目标.

This is 1.14; you are using 1.15, and the docs mention differences in 1.16. So this is a moving target.

astype 的行为与对 'blank' 数组的赋值相同:

The astype is behaving the same as assignment to 'blank' array:

In [162]: arr2 = np.zeros(arr1.shape, dt2)

In [163]: arr2
Out[163]: 
array([(0, 0., b''), (0, 0., b''), (0, 0., b'')],
      dtype=[('b', '<i8'), ('a', '<f8'), ('c', 'S3')])

In [164]: arr2[:] = arr1

In [165]: arr2
Out[165]: 
array([(1, 2., b'a'), (3, 4., b'b'), (5, 6., b'c')],
      dtype=[('b', '<i8'), ('a', '<f8'), ('c', 'S3')])

In [166]: arr2[:] = arr1[['b','a','c']]

In [167]: arr2
Out[167]: 
array([(2, 1., b'a'), (4, 3., b'b'), (6, 5., b'c')],
      dtype=[('b', '<i8'), ('a', '<f8'), ('c', 'S3')])