数据处理-scipy 三维插值 RegularGridInterpolator

scipy 三维插值

现有一组 mesh datagrid 数据,主要包括坐标及该坐标对应的value。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
data = """
│ │ x y z val
0 1 1 1 0.00e+00
1 2 1 1 9.46e-07
2 3 1 1 8.44e-07
3 4 1 1 0.00e+00
4 5 1 1 2.05e-07
... ... ... ... ...
249995 96 50 50 8.07e-07
249996 97 50 50 1.35e-06
249997 98 50 50 1.03e-06
249998 99 50 50 5.56e-07
249999 100 50 50 1.40e-06

[250000 rows x 5 columns]
"""

插值获取其中任意一点 value。
对这种规则的 mesh datagrid 可以直接使用 RegularGridInterpolator

ref https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html

scipy.interpolate.RegularGridInterpolator(points, values, method='linear', bounds_error=True, fill_value=nan, *, solver=None, solver_args=None)

参数 定义 说明
points n维规则网格 数据格式举例:三维数据 (x,y,z)
x,y,z 的shape分别为 m1,m2,m3 , 必须严格为升序或者降序
values 数据 数据格式举例:values
values.shape 应该为 (m1,m2,m3)
method 插值算法 默认’linear’
可选’nearest’、’slinear’、’cubic’、’quintic’和’pchip’
bounds_error 界内判定 默认True, 越界报错;如果False,则使用fill_value
fill_value 界外填充值 默认np.nan;如果None,则外推插值
solver 求解器 插值算法为 ‘slinear’、’cubic’和’quintic’时可用
solver_args 求解器参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import numpy as np
import pandas as pd
from scipy.interpolate import RegularGridInterpolator

df = pd.read_csv('data.csv')

x = np.sort(df['x'].unique())
y = np.sort(df['y'].unique())
z = np.sort(df['z'].unique())

# 将数据值转为三维数组
values = df['val'].values.reshape(len(x), len(y), len(z))
print(values)

mesh_intp = RegularGridInterpolator((x, y, z), values, bounds_error=False, fill_value=None)

pos = (50.5, 45.5, 3.2)
res = mesh_intp(pos)