0

example code:

import numpy as np
a=np.ones((1,4,4))
shape1=a[0,:,[0,1,2]].shape
shape2=a[0][:,[0,1,2]].shape

result:

shape1 is (3,4) and shape2 is (4,3)

Need help! I think they should have same results.

  • print the 2 array – Will Nov 09 '22 at 08:09
  • 2
    read the docs about indexing, use `a = np.arange(16).reshape((1,4,4))` instead and as @Will says, print the 2 arrays to check what these operations do. https://numpy.org/doc/stable/user/basics.indexing.html – Julien Nov 09 '22 at 08:19
  • That slice in the middle creates a documented mix of basic and advanced indexing. The slice dimension is placed last. The question comes up every once in a while on SO. https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing – hpaulj Nov 09 '22 at 08:20
  • thanks for your answer。i understand from the example in numpy doc here:https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing – 孟文明 Nov 09 '22 at 13:18

2 Answers2

0

Because in one you are taking rows 0, 1 and 2 and in the other you are taking columns 0, 1 and 2.

An easy way to see this is by generating a matrix with different values.

a = np.array([[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]])

enter image description here

a[0,:,[0,1,2]]

enter image description here

a[0][:, [0, 1, 2]]

enter image description here

Basically, in the first case, you are saying "I want from all ([:]) the 2-dimensional matrices of the zero position ([0]) of my 3-dimensional vector the rows 0, 1 and 2".

In the second case, you are saying, "I want from the 2-dimesnional matrices of the zero position ([0]) of my 3-dimensional vector all rows ([:]) and columns 0, 1 and 2."

Iker
  • 119
  • 1
  • 6
  • thanks for your answer。 But I'm still confused. i found a[0,:,[0,1,2]] and a[0,:,0:3] still produce different result. can you explain the difference between them ? – 孟文明 Nov 09 '22 at 12:26
0

In the first case, a[0,:,[0,1,2]] is equal to:

np.array([a[0,:,0], a[0,:,1], a[0,:,2]])

They share the same shape.

Cooper
  • 1