基于字段nam的结构化numy数组的在位排序

2024-03-29 06:50:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有很多数据存储在结构化numy数组中,例如:

In []: data
Out[]: 
array([(1.0, 1.001, 1.002, 1.003), (2.0, 2.001, 2.002, 2.003),
       (3.0, 3.001, 3.002, 3.003), (4.0, 4.001, 4.002, 4.003)], 
      dtype=[('f3', '<f8'), ('f0', '<f8'), ('f1', '<f8'), ('f2', '<f8')])

我的数据中特征的顺序不一致。为了处理数据,我想根据字段名对数组进行排序,例如:

^{pr2}$

根据字段名进行排序时使用:

data = data[order]

这将产生预期结果:

In []: data
Out[]:
array([(1.001, 1.002, 1.003, 1.0) (2.001, 2.002, 2.003, 2.0)
       (3.001, 3.002, 3.003, 3.0) (4.001, 4.002, 4.003, 4.0)]
      dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<f8')])

然而,在我研究如何进行排序时,我读了几遍以使用numpy.take来避免复制(例如sorting numpy structured and record arrays is very slow)。在

有没有办法把就地排序应用到我的问题上?我的方法行不通,因为numpy.take需要整数作为索引。请记住,我试图根据字段名而不是对数据中包含的值进行排序,因此我认为通常的numpy.sort也不起作用。在

In []: np.take(data, order, out=data)
Out[]: 
Traceback (most recent call last):
File "C:/PycharmWorkspace/test.py", line 30, in <module>
np.take(data, [int('f0'), int('f1'), int('f2'), int('f3')], out=data)
ValueError: invalid literal for int() with base 10: 'f0'

Tags: 数据innumpydata排序数组outint