Implicit transposing in numpy array indexing

天涯浪子 提交于 2021-02-16 18:33:31

问题


I came across a weird problem:

from numpy import zeros, arange
aa = zeros([1, 3, 10])
aa[0, :, arange(5)].shape

Running this gives me (5,3), but I'm expecting (3,5).

However, running the following gives me (3,5) as expected.

aa = zeros([3, 10])
aa[:, arange(5)]

This is easy to fix as part of my program, but it completely ruined my belief.

I tried to search for similar questions that have already been answered but have no idea what to search for.

Thank you and Happy Chinese New Year!


回答1:


This is a case of mixed basic and advanced indexing. The 1st and last indexes are numeric, and the middle a slice. It selects values based the 0 and arange(5), and appends the : dimension at the end.

aa[0, :, :5].shape

should produce the (3,5) you expect.

http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing

Numpy 3D array transposed when indexed in single step vs two steps contrasts the behavior of

y = x[0, :, mask]
z = x[0, :, :][:, mask]

Be sure to check the comments to my answer, for the argument that this is a bug and will be fixed.



来源:https://stackoverflow.com/questions/35306372/implicit-transposing-in-numpy-array-indexing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!