Why numpy works of this way on 1d slicing?

Question:

Hello I am checking slicing in numpy and I have the following two codes:

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
arr[0:2, 1:4]

that returns

[[2, 3, 4], [7, 8, 9]]

in the first case, the index go from 0 to 2

[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
  0  1  2  3  4    0  1  2  3  4

In the first slicing [0:2] is picking 3 numbers 2th inclusive

2, 3, 4

But in the second it isn’t and np only gets 3 numbers instead of 4 like in the other.

Why one of this is picking the end in this case 2, but in another case not?

For 1D the same behavior and end index are not taken into account.

Thanks.

Asked By: Tlaloc-ES

||

Answers:

It’s not picking the end index in any case.

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
arr[0:2, 1:4]
0 ⇢[[1, 2, 3, 4, 5],
1 ⇢ [6, 7, 8, 9, 10]]
      ⇡  ⇡  ⇡  ⇡   ⇡
      0  1  2  3  4

In the first slice 0:2, 2 elements are picked up 0 and 1, which results in

0 ⇢[1, 2, 3, 4, 5]
1 ⇢[6, 7, 8, 9, 10]

Then, in each of those, 1,2 and 3rd elements(1:4) are picked up resulting in

0 ⇢[2, 3, 4]
1 ⇢[7, 8, 9]
     ⇡  ⇡  ⇡   
     1  2  3  
Answered By: TheMaster

Maybe this example help you. I recommend this : Understanding slicing

arr = np.array([
#col:0 , 1,  2,  3,  4
    [1,  2,  3,  4,  5],  # <- row : 0
    [6,  7,  8,  9,  10], # <- row : 1
    [11, 12, 13, 14, 15]  # <- row : 2
])

# Slicing : 0:2 -> 0,1
# Slicing : 1:4 -> 1,2,3
arr[ 0:2,  1:4]
#   ^row^ ^col^

Output:

array([[2, 3, 4],
       [7, 8, 9]])
Answered By: I'mahdi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.