10

I have an array of 5 numbers:

A = [10, 20, 40, 80, 110]

I need to create a new array with a 10nth length numbers.

The extra numbers could be the average number between the two # of A.

for example: EDIT B = [10 , 15 , 20 ,30, 40, 60, 80, 95, 110 ]

Is it possible using a scipy or numpy function ?

Ruggero Turra
  • 16,929
  • 16
  • 85
  • 141
user1640255
  • 1,224
  • 3
  • 19
  • 25

3 Answers3

11

Use numpy.interp:

import numpy as np
Y = [10, 20, 40, 80, 110]
N = len(Y)
X = np.arange(0, 2*N, 2)
X_new = np.arange(2*N-1)       # Where you want to interpolate
Y_new = np.interp(X_new, X, Y) 
print(Y_new)

yields

[  10.   15.   20.   30.   40.   60.   80.   95.  110.]

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
5

Using this answer:

In [1]: import numpy as np

In [2]: a = np.array([10, 20, 40, 80, 110])

In [3]: b = a[:-1] + np.diff(a)/2

In [4]: c = np.empty(2 * a.size -1)

In [5]: c[::2] = a

In [6]: c[1::2] = b

In [7]: c
Out[7]: array([  10.,   15.,   20.,   30.,   40.,   60.,   80.,   95.,  110.])
Community
  • 1
  • 1
Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • I like this better, much more "numpythonic". Although I realized that our two answers have different `dtype=float` and `dtype=int` in the final array (due to only dividing by even numbers). – Hooked May 05 '13 at 19:34
2

You're not quite doubling it, as you only what the average values in between. You are also missing 40 as @LevLevitsky points out in a comment.

import numpy as np
A = np.array([10, 20, 40, 80, 110])
avg = (A[:-1] + A[1:])/2

B = []
for x1, x2 in zip(A, avg):
    B.append(x1)
    B.append(x2)
B.append(A[-1])

B = np.array(B)
print B

Gives:

[ 10  15  20  30  40  60  80  95 110]
Hooked
  • 84,485
  • 43
  • 192
  • 261
  • 1
    @user1640255 No problem, we are happy to help. Make sure that you up-vote and select the best answer. I see from your profile that you haven't accepted any answers yet. Do that! It helps us "close" a question, knowing that you've found a solution. – Hooked May 05 '13 at 19:49