有什么方法可以用 pandas 进行二维插值吗?
Is there any way to interpolate in 2D with pandas?
我的数据框看起来像:
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"
,即使它们不在 df 中。
例如:对于 X=10
和 Y=50
.
,我可以很容易地得到 "Val"
但是,假设我想要不在数据框中的 X=15
和 Y=15
?是否可以提取相同的? Pandas 有这样的功能吗?
作为机器学习的切入点,这可能是试验线性回归模型的好方法:
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.])
我不知道 pandas,但你可以通过 scipy.interpolate.interp2d
:
f = interp2d(x = df['X'], y = df['Y'], z = df['Val'])
然后可以查看给定点的函数值(x, y)
:
>>> f(15, 15)
array([17.97919182])
我的数据框看起来像:
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"
,即使它们不在 df 中。
例如:对于 X=10
和 Y=50
.
"Val"
但是,假设我想要不在数据框中的 X=15
和 Y=15
?是否可以提取相同的? Pandas 有这样的功能吗?
作为机器学习的切入点,这可能是试验线性回归模型的好方法:
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.])
我不知道 pandas,但你可以通过 scipy.interpolate.interp2d
:
f = interp2d(x = df['X'], y = df['Y'], z = df['Val'])
然后可以查看给定点的函数值(x, y)
:
>>> f(15, 15)
array([17.97919182])