[英]Type error, and then ValueError: x and y must have same first dimension
[英]ValueError: x and y must have same first dimension exception is thrown, but x and y are of the same type and length
因此,当我试图弄清楚如何获得 numpy 数组的平均平均值并绘制它时。 我收到以下错误消息:
'ValueError: x and y must have same first dimension, but have shapes (1L,) and (10L,)'
我的代码如下:
t = np.arange(0,100, 10)
x = np.arange(10)
print type(t), type(x), len(t), len(x), t, x
average = np.array([])
for x in range(len(t)):
mask = np.ones(len(t), dtype=bool)
if x is not 0:
mask[x-1] = False
mask[x]= False
if x+1 is not len(t):
mask[x+1]= False
b = np.ma.array(t,mask=mask)
average = np.append(average, np.ma.average(b))
plt.plot(x, t)
plt.plot(x, average)
plt.show'
打印返回以下内容
<type 'numpy.ndarray'> <type 'numpy.ndarray'> 10 10 [ 0 10 20 30 40 50 60 70 80 90] [0 1 2 3 4 5 6 7 8 9]
但是然后在绘图中它会引发错误。 我不明白为什么,因为 x 和 t 的长度和类型相同。
我什至试图重现它,但它突然起作用了:
f = np.arange(10)
g = np.arange(0,100, 10)
print f, g
plt.plot(f, g)
[0 1 2 3 4 5 6 7 8 9] [ 0 10 20 30 40 50 60 70 80 90]
谁能告诉我为什么它不起作用? 为什么当我尝试重现它时它会起作用?
您的列表x
的名称被 for 循环中的x
覆盖。 将其更改为for i in range
它将起作用,或者更改您的列表名称:
t = np.arange(0,100, 10)
x = np.arange(10)
average = np.array([])
for i in range(len(t)):
mask = np.ones(len(t), dtype=bool)
if i is not 0:
mask[i-1] = False
mask[i]= False
if i+1 is not len(t):
mask[i+1]= False
b = np.ma.array(t,mask=mask)
average = np.append(average, np.ma.average(b))
plt.plot(x, t)
plt.plot(x, average)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.