python numpy 切片符号(COMMA VS STANDARD INDEX)

python numpy slice notation (COMMA VS STANDARD INDEX)

使用逗号和为更传统的读者显式展开索引引用之间是否存在性能差异?由于两者似乎产生相同的结果,但后者对某些人来说可能更直观

x = numpy.array([[1,2,3,4],
                 [5,6,7,8]])

comma_method = x[0,1:3] 
>>> numpy.array([2,3])

conventional method = x[0][1:3]
>>> numpy.array([2,3])

几乎总是使用逗号,不是出于性能原因,而是因为两次索引并不完全等效:

In [2]: x = numpy.array([[0, 1], [2, 3]])

In [3]: x[:1, :1]
Out[3]: array([[0]])

In [4]: x[:1][:1]
Out[4]: array([[0, 1]])

也就是说,逗号似乎也有速度优势:

In [7]: %timeit x[0][0]
The slowest run took 25.41 times longer than the fastest. This could mean that a
n intermediate result is being cached 
1000000 loops, best of 3: 357 ns per loop

In [8]: %timeit x[0, 0]
The slowest run took 41.92 times longer than the fastest. This could mean that a
n intermediate result is being cached 
1000000 loops, best of 3: 148 ns per loop

我不确定最慢的 运行 和最快的 运行 有这么大的时差。

第二种情况效率较低,因为在随后索引的第一个索引之后创建了一个新的临时数组。