user2985656 user2985656 - 1 month ago 8
Python Question

In numpy, why multi dimension array d[0][0:2][0][0] returning not two elements

In [136]: d = np.ones((1,2,3,4))

In [167]: d[0][0][0:2][0]
Out[167]: array([ 1., 1., 1., 1.])


as shown above, why it's not returning exactly 2 elements

Answer

Look at the array itself. It should be self explanatory

>>> d
array([[[[ 1.,  1.,  1.,  1.],
         [ 1.,  1.,  1.,  1.],
         [ 1.,  1.,  1.,  1.]],

        [[ 1.,  1.,  1.,  1.],
         [ 1.,  1.,  1.,  1.],
         [ 1.,  1.,  1.,  1.]]]])
# first you grab the first and only element
>>> d[0]
array([[[ 1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.]],

       [[ 1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.],
        [ 1.,  1.,  1.,  1.]]])
# then you get the first element out of the two groups
>>> d[0][0]
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])
# thirdly, you get the two first elements as a list
>>> d[0][0][0:2]
array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]])
# finally, you get the first element of the list
>>> d[0][0][0:2][0]
array([ 1.,  1.,  1.,  1.])
Comments