Skip to content Skip to sidebar Skip to footer

Divide Each Element By The Next One In NumPy Array

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

Solution 1:

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

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

To get floating point divisions -

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

Or put from __future__ import division and then use a[:-1]/a[1:].

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

Sample run -

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

Post a Comment for "Divide Each Element By The Next One In NumPy Array"