将每个元素除以NumPy数组中的下一个元素

问题描述:

我希望能够将一维numpy数组中的值除以以下值.例如,我有一个看起来像这样的数组.

What I hope to do is be able to divide a value in a 1 dimensional numpy array by the following value. For example, I have an array that looks like this.

[ 0 20 23 25 27 28 29 30 30 22 20 19 19 19 19 18 18 19 19 19 19 19 ]

我想这样做:

0/20 #0th value divided by 1st value
20/23 #1st value divided by 2nd value
23/25 #2nd value divided by 3rd value
25/27 #3rd value divided by 4th value
etc...

我可以轻松地通过循环来完成此操作,但是我想知道是否有更有效的方法可以执行numpy操作.

I can easily do it through a loop, however I was wondering if there is a more efficient way of doing this with numpy operations.

获取两个

Get two Slices - One from start to last-1, another from start+1 to last and perform element-wise division -

a[:-1]/a[1:]

获得浮点数除法-

np.true_divide(a[:-1],a[1:])

或放入from __future__ import division,然后使用a[:-1]/a[1:].

通过 views 进入输入数组,可以真正有效地访问这些切片用于按元素划分操作.

Being views into the input array, these slices are really efficiently accessed for element-wise division operation.

样品运行-

In [56]: a    # Input array
Out[56]: array([96, 81, 48, 53, 18, 92, 79, 43, 13, 69])

In [57]: from __future__ import division

In [58]: a[:-1]/a[1:]
Out[58]: 
array([ 1.18518519,  1.6875    ,  0.90566038,  2.94444444,  0.19565217,
        1.16455696,  1.8372093 ,  3.30769231,  0.1884058 ])

In [59]: a[0]/a[1]
Out[59]: 1.1851851851851851

In [60]: a[1]/a[2]
Out[60]: 1.6875

In [61]: a[2]/a[3]
Out[61]: 0.90566037735849059