Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy range created using percentage increment

Tags:

pandas

numpy

I would like to create a numpy range from start to stop using a (fixed) percentage increment based on the previous number eg start=100 increment=2% to get 100, 102, 104.04, 106.12 etc

Obviously this can be done by iterating over a list or, more elegantly, using a generator:

def pct_incrementer(start, stop, step_pct):
    val = start
    yield val
    while True:
        val += val * step_pct
        if val >= stop:
            break
        yield val

 np.array(list(pct_incrementer(100, 200, 0.02)))
 # or (as I've just learned!)
 np.fromiter(pct_incrementer(100, 200, 0.02), float)  

Does numpy (or pandas) have a function to do this natively?? (cos I can't find one!). Is there, perhaps a way of manipulating np.array([100] * 10) to do the same thing?

Thanks!

like image 525
user908094 Avatar asked Dec 05 '25 14:12

user908094


1 Answers

You can use full and cumprod:

xs = 100 * np.full(np.log(2.0)/np.log(1.02),1.02).cumprod()

like image 120
hilberts_drinking_problem Avatar answered Dec 07 '25 14:12

hilberts_drinking_problem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!