为什么切片使用"冒号和逗号"与使用索引集合不同

时间:2018-05-30 09:26:50

标签: python numpy numpy-slicing

为什么切片使用"冒号和逗号"与使用索引集合不同?

以下是我希望产生相同结果的示例,但它没有:

import numpy as np

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

print(a[[0,1],[0,1]])
# Output
# [[ 1  2  3]
#  [10 11 12]]

print(a[:,[0,1]])
# Output
# [[[ 1  2  3]
#   [ 4  5  6]]
#  [[ 7  8  9]
#   [10 11 12]]]

为什么它们不相同?

1 个答案:

答案 0 :(得分:1)

在第一种情况下,您使用2个相同长度的列表索引数组public class GlobalGrpcExceptionHandler implements ServerInterceptor { @Override public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata requestHeaders, ServerCallHandler<ReqT, RespT> next) { ServerCall.Listener<ReqT> delegate = next.startCall(call, requestHeaders); return new SimpleForwardingServerCallListener<ReqT>(delegate) { @Override public void onHalfClose() { try { super.onHalfClose(); } catch (Exception e) { call.close(Status.INTERNAL .withCause (e) .withDescription("error message"), new Metadata()); } } }; } } ,这相当于使用2个相同形状的数组进行索引(请参阅numpy docs on arrays as indices)。

因此,输出为a(与a[0,0])和a[0,0,:]相同,是索引数组的元素组合。预计这将返回形状2,3的数组。 2因为它是索引数组的长度,因为它是未编入索引的轴。

然而,在第二种情况下,结果为a[1,1](相当于a[:,0])和a[:,0,:]。因此,这里预期的结果是一个数组,其第一和第三维相当于原始数组,第二维等于2,索引数组的长度(这里与第二轴的原始大小相同)

为了清楚地表明这两个操作显然不相同,我们可以尝试假设a[:,1]与轴与第三轴长度相同的范围之间的等价,这将导致:

:

这是因为索引数组没有元素组合可能。与此相反,print(a[[0,1],[0,1],[0,1,2]]) IndexError Traceback (most recent call last) <ipython-input-8-110de8f5f6d8> in <module>() ----> 1 print(a[[0,1],[0,1],[0,1,2]]) IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (2,) (2,) (3,) 将返回整个数组,a[:,:,:]返回a[[0,1],[0,1],[0,2]],其中预期的是一个长度为2的一维数组,与索引数组一样。