简体   繁体   中英

Interpolating numpy array in python

I am trying to interpolate some values contained in a list by first turning the lists into arrays and perform the calculations.

However, I need to write the formula three times and I need to specify the indexes manually.

Here is my code so far

import numpy as np
data1 = [(5,), (4,), (6,)]
data2 = [(2,), (8,), (9,)]
data3 = [(3,), (1,), (7,)]

x1 = [(4, 2, 1)]
x2 = [(6, 9, 7)]
y1 = [(1,)]
y2 = [(3,)]

data1 = np.array(data1)
x1 = np.array(x1)
x2 = np.array(x2)
y1 = np.array(y1)
y2 = np.array(y2)

new1 = ((data1-x1[0,0])/(x2[0,0]-x1[0,0]))*(y2-y1)+y1
print(new1)

new2 = ((data2-x1[0,1])/(x2[0,1]-x1[0,1]))*(y2-y1)+y1
print(new2)

new3 = ((data3-x1[0,2])/(x2[0,2]-x1[0,2]))*(y2-y1)+y1
print(new3)

and the output is

[[2.]
 [1.]
 [3.]]
[[1.        ]
 [2.71428571]
 [3.        ]]
[[1.66666667]
 [1.        ]
 [3.        ]]

I was wondering if anyone has a better and faster way to do this automatically, without writing everything manually?

Just put data1 , data2 etc in an array and your expression will just work with element-wise and broadcasted computations.

>>> data = np.hstack([data1, data2, data3])
>>> new = (data - x1) / (x2 - x1) * (y2 - y1) + y1
>>> new
array([[2.        , 1.        , 1.66666667],
       [1.        , 2.71428571, 1.        ],
       [3.        , 3.        , 3.        ]])

If you want the results to be in column-like vectors of shape (3, 1) each, then do new = new[...,None] and then new[:,0] will give you the same exact result as your new1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM