简体   繁体   中英

ValueError: x and y must have same first dimension exception is thrown, but x and y are of the same type and length

So while i'm trying to figure out how the get the mean average of an numpy array and to plot it. I got the following error message:

'ValueError: x and y must have same first dimension, but have shapes (1L,) and (10L,)'  

My code is as follows:

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'

the print returns the following

<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]

but then at the plots it throws the error. I don't understand why because x and t are of the same length and type.

I even tried to reproduce it but then it suddenly works:

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]

在此处输入图片说明

Can anybody tell me why it doesn't work? and why it does work when I try to reproduce it?

The name of your list x gets overwritten by the x in your for loop. Change it to for i in range and it will work, or alternatively change the name of your list:

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()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM