1

Let's say I have a simple array, like this one:

import numpy as np
a = np.array([1,2,3])

Which returns me, obviously:

array([1, 2, 3])

I'm trying to add calculated values between consecutive values in this array. The calculation should return me n equally spaced values between it's bounds.

To express myself in numbers, let's say I want to add 1 value between each pair of consecutive values, so the function should return me a array like this:

array([1, 1.5, 2, 2.5, 3])

Another example, now with 2 values between each pair:

array([1, 1.33, 1.66, 2, 2.33, 2.66, 3])

I know the logic and I can create myself a function which will do the work, but I feel numpy has specific functions that would make my code so much cleaner!

3 Answers 3

1

If your array is

import numpy as np

n = 2
a = np.array([1,2,5])

new_size = a.size + (a.size - 1) * n

x = np.linspace(a.min(), a.max(), new_size)
xp = np.linspace(a.min(), a.max(), a.size)
fp = a
result = np.interp(x, xp, fp)

returns: array([1. , 1.33333333, 1.66666667, 2. , 2.66666667, 3.33333333, 4. ])

If your array is always evenly spaced, you can just use

new_size = a.size + (a.size - 1) * n
result = np.linspace(a.min(), a.max(), new_size)
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic! You even predicted the problem I didn't know I had
0

Using linspace should do the trick:


a = np.array([1,2,3])
n = 1

temps = []

for i in range(1, len(a)):
    temps.append(np.linspace(a[i-1], a[i], num=n+1, endpoint=False))

# Add last final ending point
temps.append(np.array([a[-1]]))
new_a = np.concatenate(temps)
print(new_a)

Comments

0

Try with np.arange:

a = np.array([1,2,3])
n = 2
print(np.arange(a.min(), a.max(), 1 / (n + 1)))

Output:

[1.         1.33333333 1.66666667 2.         2.33333333 2.66666667]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.