[英]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.