Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create equal spaced values in between unequal spaced values in Python?

I have an array A (variable) of the form:

A = [1, 3, 7, 9, 15, 20, 24]

Now I want to create 10 (variable) equally spaced values in between values of array A so that I get array B of the form:

B = [1, 1.2, 1.4, ... 2.8, 3, 3.4, 3.8, ... , 6.6, 7, 7.2, ..., 23.6, 24]

In essence B should always have the values of A and equally spaced values in between values of A.

I did solve this by using the code:

import numpy as np
A = np.array([1, 3, 7, 9, 15, 20, 24])
B = []
for i in range(len(A) - 1):
    B = np.append(B, np.linspace(A[i], A[i + 1], 11))
print (B)

But does NumPy already have any function or are there any other better methods to create such array.

like image 968
nxcr Avatar asked Dec 08 '22 04:12

nxcr


1 Answers

Alternative method using interpolation instead of concatenation:

n = 10
x = np.arange(0, n * len(A), n)       # 0, 10, .., 50, 60
xx = np.arange((len(A) - 1) * n + 1)  # 0, 1, .., 59, 60
B = np.interp(xx, x, A)

Result:

In [31]: B
Out[31]: 
array([  1. ,   1.2,   1.4,   1.6,   1.8,   2. ,   2.2,   2.4,   2.6,
         2.8,   3. ,   3.4,   3.8,   4.2,   4.6,   5. ,   5.4,   5.8,
         6.2,   6.6,   7. ,   7.2,   7.4,   7.6,   7.8,   8. ,   8.2,
         8.4,   8.6,   8.8,   9. ,   9.6,  10.2,  10.8,  11.4,  12. ,
        12.6,  13.2,  13.8,  14.4,  15. ,  15.5,  16. ,  16.5,  17. ,
        17.5,  18. ,  18.5,  19. ,  19.5,  20. ,  20.4,  20.8,  21.2,
        21.6,  22. ,  22.4,  22.8,  23.2,  23.6,  24. ])

This should be faster than the other solutions, since it does not use a Python for-loop, and does not do the many calls to linspace. Quick timing comparison:

In [58]: timeit np.interp(np.arange((len(A) - 1) * 10 + 1), np.arange(0, 10*len(A), 10), A)
100000 loops, best of 3: 10.3 µs per loop

In [59]: timeit np.append(np.concatenate([np.linspace(i, j, 10, False) for i, j in zip(A, A[1:])]), A[-1])
10000 loops, best of 3: 94.2 µs per loop

In [60]: timeit np.unique(np.hstack(np.linspace(a, b, 10 + 1) for a, b in zip(A[:-1], A[1:])))
10000 loops, best of 3: 140 µs per loop
like image 50
Bas Swinckels Avatar answered Mar 18 '23 12:03

Bas Swinckels