Skip to main content
 首页 » 编程设计

python之A[i] 和 A[i, :] in n-dimensional(n>1) numpy array 有什么区别

2025年05月04日21cyq1162

假设 X 是一个 n 维 (n>1) numpy 数组。

X[i] 和 X[i,:] 有区别吗?

例如,

X = np.zeros((3,3)) 
 
print(X[i]) 
 #[ 0.  0.  0.] 
print(X[i,:]) 
 #[ 0.  0.  0.] 

我觉得完全一样,但我猜,我觉得有一些不同

访问速度方面。

不过我也不是很清楚。

请您参考如下方法:

https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing

If the number of objects in the selection tuple is less than N , then : is assumed for any subsequent dimensions.

An integer, i, returns the same values as i:i+1 except the dimensionality of the returned object is reduced by 1. In particular, a selection tuple with the p-th element an integer (and all other entries :) returns the corresponding sub-array with dimension N - 1.

它们是一样的。如另一个答案所示,时间上存在差异,但时间在 ns 中,其中 Python 解析时间和函数调用层可能会有所不同。但我欢迎任何基于对 numpy 代码的实际阅读的更正。

In [190]: X = np.zeros((3,3)) 
In [191]: X.__array_interface__ 
Out[191]:  
{'data': (45249072, False), 
 'strides': None, 
 'descr': [('', '<f8')], 
 'typestr': '<f8', 
 'shape': (3, 3), 
 'version': 3} 

切片属性相同:

In [192]: X[0].__array_interface__ 
Out[192]:  
{'data': (45249072, False), 
 'strides': None, 
 'descr': [('', '<f8')], 
 'typestr': '<f8', 
 'shape': (3,), 
 'version': 3} 
In [193]: X[0,:].__array_interface__ 
Out[193]:  
{'data': (45249072, False), 
 'strides': None, 
 'descr': [('', '<f8')], 
 'typestr': '<f8', 
 'shape': (3,), 
 'version': 3} 

时间安排:

In [194]: timeit X[0] 
172 ns ± 2.43 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) 
In [195]: timeit X[0,...] 
175 ns ± 0.105 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) 
In [196]: timeit X[0,:] 
264 ns ± 15 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 

比较返回副本的时间(相对于 View ):

In [199]: timeit X[[0]] 
6.73 µs ± 48.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) 

和列的相同索引:

In [206]: timeit X[:,1] 
262 ns ± 5.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) 
In [207]: timeit X[...,1] 
177 ns ± 2.15 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each) 

(对于一个更大的数组,我得到了相同的时间 - 支持任何时间差异发生在解析/设置过程中的想法,而不是在 View 的实际构建过程中。)