如何从Python Slice Object生成numpy.ufunc.reduceat索引 [英] How can a numpy.ufunc.reduceat indices be generated from Python Slice Object

查看:115
本文介绍了如何从Python Slice Object生成numpy.ufunc.reduceat索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个像x[p:-q:n]x[::n]的切片,我想用它来生成要传递到numpy.ufunc.reduceat(x, [p, p + n, p + 2 * n, ...])numpy.ufunc.reduceat(x, [0, n, 2 * n, ...])的索引.完成它的最简单,最有效的方法是什么?

Say I have a slice like x[p:-q:n] or x[::n] I want to use this to generate the index to be passed into numpy.ufunc.reduceat(x, [p, p + n, p + 2 * n, ...]) or numpy.ufunc.reduceat(x, [0, n, 2 * n, ...]). What is the easiest and efficient way to get it done?

推荐答案

以评论为基础:

In [351]: x=np.arange(100)
In [352]: np.r_[0:100:10]
Out[352]: array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
In [353]: np.add.reduceat(x,np.r_[0:100:10])
Out[353]: array([ 45, 145, 245, 345, 445, 545, 645, 745, 845, 945], dtype=int32)
In [354]: np.add.reduceat(x,np.arange(0,100,10))
Out[354]: array([ 45, 145, 245, 345, 445, 545, 645, 745, 845, 945], dtype=int32)
In [355]: np.add.reduceat(x,list(range(0,100,10)))
Out[355]: array([ 45, 145, 245, 345, 445, 545, 645, 745, 845, 945], dtype=int32)
In [356]: x.reshape(-1,10).sum(axis=1)
Out[356]: array([ 45, 145, 245, 345, 445, 545, 645, 745, 845, 945])

和时间:

In [357]: timeit np.add.reduceat(x,np.r_[0:100:10])
The slowest run took 9.30 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 31.2 µs per loop
In [358]: timeit np.add.reduceat(x,np.arange(0,100,10))
The slowest run took 85.75 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 6.69 µs per loop
In [359]: timeit np.add.reduceat(x,list(range(0,100,10)))
The slowest run took 4.31 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 11.9 µs per loop
In [360]: timeit x.reshape(-1,10).sum(axis=1)
The slowest run took 5.57 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 11.5 µs per loop

带有arange

reduceat看起来最好,但是应该在更真实的数据上进行测试.在这种尺寸下,速度并没有什么不同.

reduceat with arange looks best, but it should be tested on more realistic data. Speeds aren't that different at this size.

r_的值是它使您可以使用方便的切片表示法.它在一个名为index_tricks.py的文件中.

The value of r_ is that it lets you use the convenient slicing notation; it's in a file called index_tricks.py.

元素为x的元素为10000时,时间分别为80、46、238、51.

With a 10000 element x, times are 80, 46, 238, 51.

这篇关于如何从Python Slice Object生成numpy.ufunc.reduceat索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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