How does slice indexing work in numpy array

℡╲_俬逩灬. 提交于 2020-07-30 10:03:32

问题


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 understand why row_r1.shape is (4,) and row_r2.shape is (1,4)

Shouldn't their shape all equal to (4,)?


回答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:

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:

Returning:

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

shape

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




回答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!



来源:https://stackoverflow.com/questions/55581540/how-does-slice-indexing-work-in-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!