使用变量指定np.ogrid步长时出现AttributeError的原因
numpy.ogrid使用字符串步长报错的原因与解决方法
错误原因
- np.ogrid的切片语法中,
0:1:10j里的10j是复数类型,numpy通过复数的虚部数值确定要生成的网格点数。 - 若传入字符串
"10j",numpy无法将其解析为合法的步长参数,内部处理时会把0:1:"10j"识别为无效切片构造,进而抛出AttributeError: 'tuple' object has no attribute 'step'错误。 - 字符串
"10j"与复数10j属于不同数据类型,前者是str,后者是complex,因此二者比较结果为False,只有同类型的"10j" == "10j"才会返回True。
解决方法
无需通过字符串拼接构造步长,直接生成复数类型的参数即可:
- 若点数是固定值,直接写
10j即可(如你提供的可运行示例)。 - 若点数是变量,通过数字乘以
1j或complex(0, 点数)构造复数:
修改后的可运行代码片段
# 替换原字符串拼接的部分 n = 10 rows = n * 1j # 等价于 complex(0, 10) columns = n * 1j xi, yi = np.ogrid[0:1:rows, 0:1:columns]
验证复数类型的测试代码
a = 10 * 1j print(type(a)) # 输出 <class 'complex'> print(a == 10j) # 输出 True
完整修正后的代码
import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import griddata as gd # define X Y V testsample x = [0, 1, 1, 0] y = [0, 0, 1, 1] v = [1, 2, 3, 4] # create grid # Working modified example n = 10 rows = n * 1j columns = n * 1j xi, yi = np.ogrid[0:1:rows, 0:1:columns] X1 = xi.reshape(xi.shape[0]) Y1 = yi.reshape(yi.shape[1]) ar_len = len(X1)*len(Y1) X = np.arange(ar_len, dtype=float) Y = np.arange(ar_len, dtype=float) l = 0 for i in range(0, len(X1)): for j in range(0, len(Y1)): X[l] = X1[i] Y[l] = Y1[j] l+=1 #interpolate v on xy grid V = gd((x,y), v, (X,Y), method='linear') print(V) #Plot original values fig1 = plt.figure() ax1=fig1.gca() sc1=ax1.scatter(x, y, c=v, cmap=plt.hot()) plt.colorbar(sc1) ax1.set_xlabel('X') ax1.set_ylabel('Y') #Plot interpolated values fig2 = plt.figure() ax2=fig2.gca() sc2=ax2.scatter(X, Y, c=V, cmap=plt.hot()) plt.colorbar(sc2) ax2.set_xlabel('X') ax2.set_ylabel('Y') plt.show()
内容的提问来源于stack exchange,提问作者Bende
相关产品推荐
相关产品推荐

