Home > OS >  why do numpy array arr3d[0,:,[0,1,2]] and arr3d[0][:,[0,1,2]] produce different result
why do numpy array arr3d[0,:,[0,1,2]] and arr3d[0][:,[0,1,2]] produce different result

Time:11-10

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.

CodePudding user response:

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."

CodePudding user response:

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.

  • Related