gpt4 book ai didi

python - 更改订单后如何解决numpy ValueError?

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

我创建了一个 numpy 数组(考虑输入数据)并想更改顺序(一些数值运算后的输出数据)。在使用转换后的数组时,我遇到错误并找到了根本原因。请在下面找到详细信息并使用 numpy 版本 1.19.1

import numpy as np
a = np.array([1,2,3])
b = np.array([(1.5,2,3), (4,5,6)], dtype = [('col1','<f8'),('col2','<i4'),('col3','<i4')])
names_list=['col2','col1','col3']
c=b[names_list]

print(c.dtype.descr)
但是在更改字段顺序后,我遇到了以下错误。
lib\site-packages\numpy\core_internal.py”,第 114 行,在 _array_descr
引发值错误(
ValueError:dtype.descr 没有为具有重叠或乱序字段的类型定义

我做了一些分析,发现导致这个问题的“偏移”值。所以我显示了订单更改后的偏移量,如下所示,

{'names':['col2','col1','col3'], 'formats':['<i4','<f8','<i4'], 'offsets':[8,0,12], 'itemsize':16}


然后在lib\site-packages\numpy\core_internal.py中打开numpy库代码,
offset = 0
for field in ordered_fields:
if field[1] > offset:
num = field[1] - offset
result.append(('', '|V%d' % num))
offset += num
elif field[1] < offset:
raise ValueError(
"dtype.descr is not defined for types with overlapping or "
"out-of-order fields")
提前致谢 !

最佳答案

In [73]: b = np.array([(1.5,2,3), (4,5,6)], dtype = [('col1','<f8'),('col2','<i4'),('col3','<i4')])  
In [74]: b
Out[74]:
array([(1.5, 2, 3), (4. , 5, 6)],
dtype=[('col1', '<f8'), ('col2', '<i4'), ('col3', '<i4')])
在最近的版本中,结构化数组的多字段索引返回 view ;其中包括 offset作为 dtype 的一部分:
In [75]: names_list=['col2','col1','col3']                                                           
In [76]: c = b[names_list]
In [77]: c
Out[77]:
array([(2, 1.5, 3), (5, 4. , 6)],
dtype={'names':['col2','col1','col3'], 'formats':['<i4','<f8','<i4'], 'offsets':[8,0,12], 'itemsize':16})
In [78]: c.dtype
Out[78]: dtype({'names':['col2','col1','col3'], 'formats':['<i4','<f8','<i4'], 'offsets':[8,0,12], 'itemsize':16})
c是一个 View ,访问与 b 相同的数据,但以新的顺序显示字段(并使用 offset 来做到这一点)。正如您的错误所说,这些字段是乱序的。
他们提供了一个 repack_fields函数,如果你想要一个带有新顺序字段的副本(没有偏移量):
In [79]: import numpy.lib.recfunctions as rf                                                         
In [80]:
In [80]: d = rf.repack_fields(c)
In [81]: d
Out[81]:
array([(2, 1.5, 3), (5, 4. , 6)],
dtype=[('col2', '<i4'), ('col1', '<f8'), ('col3', '<i4')])
In [82]: d.dtype
Out[82]: dtype([('col2', '<i4'), ('col1', '<f8'), ('col3', '<i4')])
In [83]: d.dtype.descr
Out[83]: [('col2', '<i4'), ('col1', '<f8'), ('col3', '<i4')]
阅读 repack_fields文档了解更多详情。
https://numpy.org/doc/stable/user/basics.rec.html#accessing-multiple-fields
您的问题更有意义 savez语境:
In [106]: np.savez('struct.npz', b=b, d=d)                                                           
In [107]: np.savez('struct.npz', c=c)
...
ValueError: dtype.descr is not defined for types with overlapping or out-of-order fields
所以如果你想保存不同字段顺序的数组,你需要使用 repack获得“干净”的副本。

关于python - 更改订单后如何解决numpy ValueError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63475093/

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