【问题标题】:Is there any way to interpolate in 2D with pandas?有没有办法用熊猫进行二维插值?
【发布时间】:2021-08-14 15:37:29
【问题描述】:

我的数据框看起来像:

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 有这样的功能吗?

【问题讨论】:

  • 你的意思是this?
  • 许多替代品。使用pd.DataFrame.interpolate、numpy.interp 或scipy.interpolate.interp1d
  • 你需要二维插值,pd.DataFrame.interpolate 在这里不行。

标签: python pandas numpy math interpolation


【解决方案1】:

作为机器学习的切入点,这可能是试验线性回归模型的好方法:

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.])

【讨论】:

    【解决方案2】:

    我不知道pandas,但你可以通过scipy.interpolate.interp2d:

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

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

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

    【讨论】:

    • 太棒了。这会给我带来相当多的红利:) +1
    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 2021-07-03
    • 2019-09-22
    相关资源
    最近更新 更多