2

numpy docs的一次访问多个字段部分中,说:

请注意,无论请求的顺序如何,这些字段总是以相同的顺序返回

该文档还给出了一个示例,如下所示:

>>> x = np.array([(1.5,2.5,(1.0,2.0)),(3.,4.,(4.,5.)),(1.,3.,(2.,6.))],
        dtype=[('x','f4'),('y',np.float32),('value','f4',(2,2))])
>>> x[['x','y']]
array([(1.5, 2.5), (3.0, 4.0), (1.0, 3.0)],
     dtype=[('x', '<f4'), ('y', '<f4')])
>>> x[['y','x']]
array([(1.5, 2.5), (3.0, 4.0), (1.0, 3.0)],
     dtype=[('x', '<f4'), ('y', '<f4')])

但是,我自己使用 numpy 1.6.1 运行了代码并得到了不同的结果:

In [20]: x = np.array([(1.5,2.5,(1.0,2.0)),(3.,4.,(4.,5.)),(1.,3.,(2.,6.))],
   ....:         dtype=[('x','f4'),('y',np.float32),('value','f4',(2,2))])

In [21]: x[['x','y']]
Out[21]:
array([(1.5, 2.5), (3.0, 4.0), (1.0, 3.0)],
      dtype=[('x', '<f4'), ('y', '<f4')])

In [22]: x[['y','x']]
Out[22]:
array([(2.5, 1.5), (4.0, 3.0), (3.0, 1.0)],
      dtype=[('y', '<f4'), ('x', '<f4')])

这种行为是从 numpy 1.6 更改为 1.7 还是我错过了什么?

编辑我已经在 numpy 1.7.1 中测试了代码,结果与 numpy 1.6 相同。

4

1 回答 1

1

Looks as if the docs are just out of date.

The code which produces the resulting array is in the function _index_fields() in numpy/core/_internal.py.

There was a change between v1.5 and v1.6 on March 22nd, 2011 from...

new_dtype = [(name, dt[name]) for name in dt.names if name in fields]

...to...

new_dtype = [(name, dt[name]) for name in fields if name in dt.names]

...so the order of the fields in the resulting array changed from the order specified in the original data type to the order in which you specified the fields when you accessed them.

However, the section of the documentation cited in the OP was added on March 1st, 2011, three weeks prior to the change.

于 2013-06-21T16:53:19.240 回答