Skip to content Skip to sidebar Skip to footer

How Does Slice Indexing Work In Numpy Array

Suppose we have an array a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]]) Now I have below row_r1 = a[1, :] row_r2 = a[1:2, :] print(row_r1.shape) print(row_r2.shape) I don't

Solution 1:

I like to think of it this way. The first way row[1, :], states go get me all values on row 1 like this:

enter image description here

Returning: array([5, 6, 7, 8])

shape

(4,) Four values in a numpy array.

Where as the second row[1:2, :], states go get me a slice of data between index 1 and index 2:

enter image description here

Returning:

array([[5, 6, 7, 8]]) Note: the double brackets

shape

(1,4) Four values in on one row in a np.array.


Solution 2:

Their shapes are different because they aren't the same thing. You can verify by printing them:

import numpy as np

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

row_r1 = a[1, :]
row_r2 = a[1:2, :]

print("{} is shape {}".format(row_r1, row_r1.shape))
print("{} is shape {}".format(row_r2, row_r2.shape))

Yields:

[5 6 7 8] is shape (4,)
[[5 6 7 8]] is shape (1, 4)

This is because indexing will return an element, whereas slicing will return an array. You can however manipulate them to be the same thing using the .resize() function available to numpy arrays. The code:

import numpy as np

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

row_r1 = a[1, :]
row_r2 = a[1:2, :]

print("{} is shape {}".format(row_r1, row_r1.shape))
print("{} is shape {}".format(row_r2, row_r2.shape))
# Now resize row_r1 to be the same shape
row_r1.resize((1, 4))
print("{} is shape {}".format(row_r1, row_r1.shape))
print("{} is shape {}".format(row_r2, row_r2.shape))

Yields

[5 6 7 8] is shape (4,)
[[5 6 7 8]] is shape (1, 4)
[[5 6 7 8]] is shape (1, 4)
[[5 6 7 8]] is shape (1, 4)

Showing that you are in fact now dealing with the same shaped object. Hope this helps clear it up!


Post a Comment for "How Does Slice Indexing Work In Numpy Array"