Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

python - Implicit transposing in numpy array indexing

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!

question from:https://stackoverflow.com/questions/66057244/python-numpy-indexing-returned-shapes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...