Using Numpy Shape Output In Logic
I am using Python 2.7.5 on Windows 7. For some reason python doesn't like it when I use one of the dimensions of my numpy array to with a comparator in an if statement: a = np.arra
Solution 1:
You are creating a tuple with np.shape so you are passing (1,(4,))
so the error has nothing to do with your if, it is what is happening inside the if , you would need to use np.shape(a)[0]
but I am not fully sure what you are trying t do:
np.shape(a)[0]
Or simply a.shape[0]
Solution 2:
The problematic line is a = np.reshape(a, (1, np.shape(a)))
.
To add an axis to the front of a
I'd suggest using:
a = a[np.newaxis, ...]
print a.shape # (1, 4)
or None
does the same thing as np.newaxis
.
Solution 3:
Looks like you are trying to do the same thing as np.atleast_2d
:
defatleast_2d(*arys): # *arys handles multiple arrays
res = []
for ary in arys:
ary = asanyarray(ary)
iflen(ary.shape) == 0 :
result = ary.reshape(1, 1)
eliflen(ary.shape) == 1 : # looks like your code!
result = ary[newaxis,:]
else :
result = ary
res.append(result)
iflen(res) == 1:
return res[0]
else:
return res
In [955]: a=np.array([1,2,3,4])
In [956]: np.atleast_2d(a)
Out[956]: array([[1, 2, 3, 4]])
or it is a list:
In [961]: np.atleast_2d([1,2,3,4])
Out[961]: array([[1, 2, 3, 4]])
you can also test the ndim
attribute: a.ndim==1
Post a Comment for "Using Numpy Shape Output In Logic"