确定结果阵列的形状在numpy的切片后 [英] Determining the shape of result array after slicing in Numpy
问题描述
我有困难的时候认识的合成数组的形状如何numpy的切片后确定。比如我使用下面这个简单的code:
I have difficult time understanding how the shape of resultant array be determined after slicing in numpy. For example I am using the following simple code:
import numpy as np
array=np.arange(27).reshape(3,3,3)
slice1 = array[:,1:2,1]
slice2= array[:,1,1]
print "Content in slice1 is ", slice1
print "Shape of slice1 is ", slice1.shape
print "Content in slice2 is ",slice2
print "Shape of Slice2 is", slice2.shape
这个输出是:
Content in slice1 is
[[ 4]
[13]
[22]]
Shape of slice1 is (3, 1)
Content in slice2 is [ 4 13 22]
Shape of Slice2 is (3,)
在这两种情况下,内容是一样的(因为它应该是)。但是,他们在不同的形状。那么,如何产生的形状由numpy的决定?
In both of these cases, content is same(as it should be). But they differ in shapes. So, how does the resultant shape is determined by numpy?
推荐答案
这基本上可以归结到这一点 -
It basically boils down to this -
In [118]: a = np.array([1,2,3,4,5])
In [119]: a[1:2]
Out[119]: array([2])
In [120]: a[1]
Out[120]: 2
当你做 A [1:2]。
,你所要求的1元素的数组
When you do a[1:2]
, you are asking for an array with 1 element.
当你做 A [1]
你所要求的该索引处的元素。
When you do a[1]
you are asking for the element at that index.
类似的事情发生在你的情况。
Similar thing happens in your case.
当你这样做 - 数组[:,1:2,1]
- 这意味着从第一个维度的所有可能的指标,从第二个方面指标的子表(虽然子清单只包含一个元素),并从第三维第一个指数。所以,你回来阵列的阵列 -
When you do - array[:,1:2,1]
- it means all possible indexes from first dimension , a sub-list of indexes from second dimension (though the sub-list only contains one element) , and 1st index from third dimension. So you get back a array of arrays -
[[ 4]
[13]
[22]]
当你这样做 - 数组[:1,1]
- 这意味着从第一个维度,从第二个维度第一个指数,并从第三个层面第一个指数的所有可能的指标。所以,你会得到一个数组 -
When you do - array[:,1,1]
- it means all possible indexes from first dimension, 1st index from second dimension, and 1st index from third dimension. So you get back an array -
[4 13 22]
这篇关于确定结果阵列的形状在numpy的切片后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!