4

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!

Manigault
  • 41
  • 1

1 Answers1

4

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.

Community
  • 1
  • 1
hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • Thanks a lot! But for the last line, are you saying this is a bug and the developers are considering to fix it, or probably many people would consider it as a bug? – Manigault Feb 11 '16 at 03:31