有没有办法在pandas中进行2D插值?

4

我的数据框看起来像这样:

X   Y   Val
10  10  17
10  30  28
10  40  35
10  50  15
20  10  17
20  30  18
20  40  33
20  50  15
40  10  37
40  30  29
40  40  49
40  50  40

我想提取给定的 "X""Y" 的插值 "Val",即使它们不在数据框中。
例如:我可以很容易地得到 X=10Y=50 时的 "Val"

但是,假设我想要的是 X=15Y=15,而数据框中没有这个值。有没有可能提取相同的结果?Pandas 是否具备这种功能?


1
你是指这个吗?(https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.interpolate.html) - MattDMo
许多选择。使用 pd.DataFrame.interpolatenumpy.interpscipy.interpolate.interp1d - rafaelc
2
你需要进行二维插值,pd.DataFrame.interpolate 在这里行不通。 - mozway
2个回答

5

我对pandas不了解,但你可以通过scipy.interpolate.interp2d实现:

f = interp2d(x = df['X'], y = df['Y'], z = df['Val'])

然后,您可以检查给定点(x, y)处的函数值:

>>> f(15, 15)
array([17.97919182])

太棒了。这将为我带来相当可观的回报 :) +1 - anky

2
作为机器学习的入门点,这可能是使用线性回归模型进行实验的好方法:
import pandas as pd
from sklearn.linear_model import LinearRegression

# create a sample dataframe
data = {'X': [10, 20, 30, 40], 'Y': [10, 20, 30, 40], 'Val': [100, 200, 300, 400]}
df = pd.DataFrame.from_dict(data)

# define the target and input data for training
target = df.Val
df.drop(['Val'], axis=1, inplace=True)
input_df = df

# fit the linear regression model
regression_model = LinearRegression()
regression_model.fit(input, target)

# create another sample dataframe to test output
prediction_data = {'X': [50, 60, 70], 'Y': [50, 60, 70]}
prediction_df = pd.DataFrame.from_dict(prediction_data)

# make predictions
regression_model.predict(prediction_df)

这将产生以下输出:

array([500., 600., 700.])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接