python numpy slice表示法(COMMA VS STANDARD INDEX) [英] python numpy slice notation (COMMA VS STANDARD INDEX)

查看:88
本文介绍了python numpy slice表示法(COMMA VS STANDARD INDEX)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a performance difference between using a comma and explicitly exploding out the index references for perhaps more conventional readers? Since both seem to yield the same results but the latter may be more intuitive to some

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])

推荐答案

不是因为性能原因,大多数情况下都是用逗号表示的,而是因为两次索引并不完全等效:

Pretty much always go for the comma, not for performance reasons, but because indexing twice isn't quite equivalent:

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]])

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

That said, the comma also appears to have a speed advantage:

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

我不确定最慢的跑步和最快的跑步会有如此时差.

I'm not sure what's up with the slowest run and the fastest run having such a time difference.

这篇关于python numpy slice表示法(COMMA VS STANDARD INDEX)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆