Ranit Dholey
Ranit Dholey

Reputation: 37

Different Numpy Array Shapes Returned For Similar Value Slicing

I have a numpy array as below:

mat = np.arange(1,26).reshape(5,5)
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])

From here, if I want to slice out the 2,7,12 values I see I can do it two ways: mat[0:3,1] which returns array([ 2, 7, 12]) or mat[:3,1:2] which returns

array([[ 2],
       [ 7],
       [12]])

I am not sure how the same slicing concept fetches the same values, but with different shape. Any help understanding this will be great.

Upvotes: 1

Views: 44

Answers (1)

Gillu13
Gillu13

Reputation: 958

Numpy extends the python concept of slicing in N dimensions as you can read in the official Numpy documentation.

It is easier to understand in 1D. Consider a list of integers A=[1,2,3], A[1] will return the integer 2 while A[1:2] will return a list containing one item [2].

It is similar in 2D with Numpy arrays,in your example mat[0:3,1] returns an array of integers while mat[0:3,1:2] returns an array of arrays, each one containing a single integer.

Upvotes: 1

Related Questions