简体   繁体   English

在python中插入numpy数组

[英]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.只需将data1data2等放入数组中,您的表达式将只适用于元素和广播计算。

>>> 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 .如果您希望结果是每个形状为 (3, 1) 的列状向量,则执行new = new[...,None]然后new[:,0]将为您提供与您的完全相同的结果new1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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