【问题标题】:How can I do Python interpolation with 2D data?如何使用 2D 数据进行 Python 插值?
【发布时间】:2020-06-18 16:52:08
【问题描述】:

我是 Python 新手,我有一个简单的插值示例,我想使用“interpn”来解决。

x = np.linspace(0,1,4)
y = np.linspace(-1,1,5)

A = np.zeros((len(x), len(y)))

for i in range (1,len(x)):
    for j in range (1,len(y)):
        A[i,j] = np.sin(x[i] ** 2 + y[j] ** 2)

x1 = np.linspace(0,1,10)
y1 = np.linspace(-1,1,20)

xi,yi = np.meshgrid(x,y)
x1i,y1i = np.meshgrid(x1,y1)



int_A = interpn(xi,yi,A,x1i,y1i)

为此,我最终得到了值错误“interpn 只理解方法 'linear'、'nearest' 和 'splinef2d'”。 因此,当我将所有输入数据都设为二维数组时,如何使用“interpn”函数进行插值,或者在这种情况下使用任何其他 Python 插值函数?我也对使用所有输入数据和函数值都是 3D 数组进行 3D 插值感兴趣。 有人可以帮我解决这些问题吗? 非常感谢!

【问题讨论】:

    标签: python interpolation


    【解决方案1】:

    你看过https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html吗?

    这应该允许您将 2D 网格作为输入。

    【讨论】:

    • 感谢您的评论。是的,我做到了。 “ int_A_3 = griddata((xi, yi), A, (x1i, y1i),method='linear') ”。这是我为“griddata”函数编写的内容,但我得到了值错误“不同数量的值和点”。我不确定这是否是我将输入插入此命令的方式,这是错误的。
    【解决方案2】:

    来自 scipy api:

    scipy.interpolate.interpn(points, values, xi, method='linear', bounds_error=True, fill_value=nan)
    
    points : tuple of ndarray of float, with shapes (m1, ), …, (mn, )
    The points defining the regular grid in n dimensions.
    
    values : array_like, shape (m1, …, mn, …)
    The data on the regular grid in n dimensions.
    
    xi : ndarray of shape (…, ndim)
    The coordinates to sample the gridded data at
    

    我相信您需要将您的点进一步打包成元组。尝试 int_A = interpn((xi,yi),A,(x1i,y1i))

    在做 3D 时也一样,只需将 zi 和 z1i 添加到元组中。

    【讨论】:

    • 谢谢!我实际上已经尝试过了,值错误是“维度 0 中的点必须是一维的”。我阅读了这些类型的值错误以了解如何调整命令来克服它,但仍然没有运气
    • 我明白了。好吧,您肯定需要将参数作为元组传递,这就是该方法错误的原因。我认为潜在的问题是因为您的范围从 1 开始。尝试从零开始。
    • 非常感谢您的建议!我现在试过了,但错误信息还是一样。实际上,我还尝试使用命令行“t_xi = tuple(map(tuple, xi))”将这些二维数组转换为元组,以类似的方式对所有 xi,yi,x1i,y1i 进行。然后尝试了“int_A = interpn((t_xi, t_yi),A,(t_x1i, t_y1i))”,但它给出了同样的错误。
    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多