前言
在数学建模建立方格状态地图中,使用scipy.interpolate.griddata()插值法遇到了一些问题,经过查阅官方文档和其他的一些博文,发现解释的不是很好,所以来补充补充
问题
1、matlab的griddata()与python的scipy.interpolate.griddata()使用方法不同导致的报错
2、切片的时候,保存有原来数据的行索引导致的报错
3、数组的shape为(2, N)导致的报错
官方文档解释
链接:http://scipy.github.io/devdocs/reference/generated/scipy.interpolate.griddata.html?highlight=griddata#scipy.interpolate.griddata
函数说明:
scipy.interpolate.griddata(points, values, xi, method=‘linear’, fill_value=nan, rescale=False)
Parameters
----------
points : 2-D ndarray of floats with shape (n, D), or length D tuple of 1-D ndarrays with shape (n,).
Data point coordinates.
values : ndarray of float or complex, shape (n,)
Data values.
xi : 2-D ndarray of floats with shape (m, D), or length D tuple of ndarrays broadcastable to the same shape.
Points at which to interpolate data.
method : {‘linear’, ‘nearest’, ‘cubic’}
代码
import scipy.interpolate
import pandas as pd
import numpy as np
path = '2011A附件_数据.xls'
fi_1 = pd.read_excel(path, sheet_name='附件1')
fi_2 = pd.read_excel(path, sheet_name='附件2')
x = np.array(fi_1.iloc[2:, 0]).T
y = np.array(fi_1.iloc[2:, 1]).T
z = np.array(fi_1.iloc[2:, 2]).T
nx = np.linspace(min(x), max(x), 100)
ny = np.linspace(min(y), max(y), 100)
xx, yy = np.meshgrid(x, y) # 获得网格
coordinate_1 = np.vstack((x, y))
coordinate_2 = np.vstack((nx, ny))
zz = scipy.interpolate.griddata(coordinate_1.T, z, coordinate_2.T, method='cubic')
解决方法
matlab中的方法
zz = griddata(x,y,z,xx,yy,‘v4’)
python中的方法
zz = scipy.interpolate.griddata(coordinate_1.T, z, coordinate_2.T, method=‘cubic’)
coordinate_1.T和coordinate_2.T是shape为**(N,2)的数组形式
coordinate_1.T对应x,y**
coordinate_2.T对应xx,yy
x = fi_1.iloc[2:, 0]
使用该切片返回的第一个行索引是2,而非0。
采用 np.array(fi_1.iloc[2:, 0]).T 来解决,利用array重置索引,然后使用 .T 来把行变成列
coordinate_1.T由于这个位置只支持列向量(例[[x1,y1,z1],[x2,y2,z2]]),所以采用 .T 来转换,最终呈现shape为(N, 2)
错误提示
index 322 is out of bounds for axis 0 with size 319
(剩下的懒得粘了,欢迎大家一起来讨论)