python griddata中的错误:“builtins.IndexError:索引0超出轴0的大小为0”

时间:2013-02-21 12:07:58

标签: python-3.x indexing grid

网格数据错误

(改编自:Matplotlib contour from xyz data: griddata invalid index

我有一些与一组坐标对应的值的矩阵。我想从外部文件加载数据并使用griddata对象在点之间进行插值。但是在运行代码时我得到错误:

“builtins.IndexError:index 0超出了griddata的0号轴0”。我不知道这意味着什么?

一段示例代码:

def main():
#https://stackoverflow.com/questions/13781025/matplotlib-contour-from-xyz-data-griddata-invalid-index
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as ml

ndata = 121
ny, nx = 100, 200
xmin, xmax = 0, 10
ymin, ymax = 0, 10

Data = np.loadtxt('Data.dat')
Data = Data.flatten(1)

x = np.array([j for i in np.arange(0,11,1) for j in np.arange(0,11,1)])
y = np.array([j for i in np.arange(0,11,1) for j in np.arange(0,11,1)])
#x = np.random.randint(xmin, xmax, ndata)
#y = np.random.randint(ymin, ymax, ndata)

xi = np.linspace(xmin, xmax, nx)
yi = np.linspace(ymin, ymax, ny)
zi = ml.griddata(x, y, Data, xi, yi)

plt.contour(xi, yi, zi, 15, linewidths = 0.5, colors = 'k')
plt.pcolormesh(xi, yi, zi, cmap = plt.get_cmap('rainbow'))

plt.scatter(x, y, marker = 'o', c = 'b', s = 5, zorder = 10)
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
plt.show()

Data.dat可以从以下网址获取:http://pastebin.com/Uk8SHA1F

请注意它如何与提供x或y以及其他坐标为随机坐标(注释)的结合起作用,但是当对x和y使用理解时却不能?

1 个答案:

答案 0 :(得分:3)

“builtins.IndexError:index 0超出了griddata的0号轴0”。我不知道这意味着什么?

index 0 is out of bounds for axis 0 with size 0

如果在预期2-D时提供1-D数组,并且第一个索引超出范围,则会出现此错误。例如:

>>> np.array([])[0,:]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 0 is out of bounds for axis 0 with size 0

>>> np.array([2,4])[3,:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: index 3 is out of bounds for axis 0 with size 2

请注意,如果您没有为第二轴指定任何值,则会出现不同的错误:

>>> np.array([])[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index out of bounds