2017-01-11 2 views
0

は私がnumpy.ufunc.reduceat(x, [p, p + n, p + 2 * n, ...])numpy.ufunc.reduceat(x, [0, n, 2 * n, ...])に渡されるインデックスを生成するためにこれを使用するx[p:-q:n]またはx[::n]のようなスライスを持っていると言います。それを達成する最も簡単で効率的な方法は何ですか?はnumpy.ufunc.reduceat指数は、Pythonスライスオブジェクトから生成することができますどのように

+0

理由だけではなく 'range'を使用していませんか? 'list(range(0、len(x)、n))' – Psidom

+0

これが最も効率的ですか? –

+0

インデックスのリストが必要な場合は効率的です。 – Psidom

答えて

3

コメントのビル:

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

とタイミング:arange

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 

reduceatは最高に見えますが、それはより現実的なデータをテストする必要があります。速度はこのサイズでそれほど変わらない。

r_という値は、便利なスライス表記法を使用できるということです。それはindex_tricks.pyというファイルにあります。 10000要素x

、時間は80、46、238、51

関連する問題