简体   繁体   English

numpy数组切片,为什么有时2-d数组,有时是1-d数组

[英]numpy array slicing, why sometimes 2-d array and sometimes 1-d array

My question is about array slicing in numpy. 我的问题是关于numpy中的数组切片。 What's the logic for the following behavior? 以下行为的逻辑是什么?

x = arange(25)
x.shape = (5, 5)
# This results in a 2-d array in which rows and columns are excerpted from x
y = x[0:2, 0:2]
# But this results in a 1-d array
y2 = x[0:2, 0]

I would have expected y2 to be a 2-d array which contains the values in rows 0 and 1, column 0. 我希望y2是一个二维数组,其中包含第0行和第0列第0列的值。

You can get your expected behavior doing x[0:2, 0:1] , ie with a single item slice. 您可以使用x[0:2, 0:1]获得预期的行为,即使用单个项目切片。 But whenever a single element is selected, that dimension is collapsed. 但是,只要选择了单个元素,该尺寸就会折叠。 You may not like it, but if you think about it a little bit, you should realize it is the most consistent behavior: following your logic, x[0, 0] would be a 2d array of 1 row and 1 column, instead of the item stored at that position. 你可能不喜欢它,但如果你想一点,你应该意识到它是最一致的行为:遵循你的逻辑, x[0, 0]将是1行1列的2d数组,而不是存储在该位置的项目。

This follows standard Python conventions. 这遵循标准的Python约定。 Look at the results of these analogous expressions: 看看这些类似表达式的结果:

>>> a = [0, 1, 2, 3, 4, 5]
>>> a[4]
4
>>> a[4:5]
[4]

As you can see, one returns one item , while the other returns a list containing one item . 如您所见,一个返回一个项目 ,另一个返回包含一个项目的列表 This is always the way python works, and numpy is just following that convention, but at a higher dimension. 这总是python的工作方式,而numpy只是遵循这个约定,但是更高的维度。 Whenever you pass a slice rather than an individual item, a list is returned; 无论何时传递切片而不是单个项目,都会返回一个列表; this is true even if there are no items in the list, either because the end index is too low, or because the starting index is too high: 即使列表中没有项目也是如此,因为结束索引太低,或者因为起始索引太高:

>>> a[4:4]
[]
>>> a[6:6]
[]

So in all situations, passing a slice means "return a sequence (along the given dimension)," while passing an integer means "return a single item (along the given dimension)." 因此,在所有情况下,传递切片意味着“返回一个序列(沿着给定的维度)”,而传递整数则意味着“返回单个项目(沿着给定的维度)”。

When you access an array using a single element instead of a slice, it will collapse that dimension. 使用单个元素而不是切片访问数组时,它将折叠该维度。 For that reason, if you have 因此,如果你有

x = arange(25)
y = x[10]

You would expect y to be 10 and not array([10]) . 你会期望y10而不是array([10])

So, if you use 所以,如果你使用

y2 = x[0:2, 0]
print y2.shape
(2,)

It will collapse the second dimension. 它会破坏第二个维度。 If you want to keep that second dimension, you need to access that dimension using a slice. 如果要保留第二个维度,则需要使用切片访问该维度。

y2 = x[0:2, 0:1]
print y2.shape
(2, 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM