Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get consecutive ratios of elements python

Tags:

python

numpy

Is there a simple way to get the ratios of consecutive elements of a numpy array?

Basically something similar to numpy.diff(x)?

so if x=[1,2,10,100 ...]

I would like [0.5 ,0.2, 0.1 ...] ie [x1/x2, x2/x3 , x3/x4]

I know I can do this easily by shifting and dividing, but it seems clumsy compared to numpy.diff(x)

like image 203
shelbypereira Avatar asked Dec 19 '22 16:12

shelbypereira


2 Answers

Using numpy:

In [6]: x
Out[6]: array([   1.,    2.,   10.,  100.,  150.,   75.])

In [7]: x[:-1]/x[1:]
Out[7]: array([ 0.5       ,  0.2       ,  0.1       ,  0.66666667,  2.        ])

That might be what you meant when you said "I can do this easily by shifting and dividing", but I don't see anything clumsy about it.

like image 146
Warren Weckesser Avatar answered Dec 21 '22 11:12

Warren Weckesser


I hate to even post this, but for x = [6, 2, 4, 10],

np.exp(-np.diff(np.log(x)))

returns array([3. , 0.5, 0.4]).

like image 32
bers Avatar answered Dec 21 '22 09:12

bers