在n维(n>1)numpy数组中,A[i]和A[i,:]的区别是什么?

2024-04-25 19:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

假设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.]

我认为这是完全相同的,但在我的猜测,我认为有一些不同的地方

访问速度条款。你知道吗

但我不太清楚。你知道吗


Tags: gtnumpy地方npzeros数组条款print
3条回答

X[i]是得到X的第i个列表

X[i,:]是从X的第i个列表中切片数据

你得到了相同的结果,但实际上它们是不同的。你知道吗

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)

比较返回副本的时间(与视图相反):

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)

(对于一个更大的数组,我得到了相同的时间——支持这样一种观点,即任何时间差都发生在解析/设置过程中,而不是在视图的实际构造过程中。)

切片比较慢。我已经用%timeit证明了这一点。它测量执行时间。你知道吗

%timeit (X[0])
10000000 loops, best of 3: 163 ns per loop

使用切片:

%timeit (X[0, :])
1000000 loops, best of 3: 245 ns per loop

相关问题 更多 >