Using numpy output in boolean form
I'm using Python 2.7.5 on Windows 7. For some reason python doesn't like it when I use one of the sizes of my numpy array with a comparator in an if statement:
a = np.array([1,2,3,4])
# reshapes so that array has two dimensions
if len(np.shape(a)) == 1:
a = np.reshape(a, (1, np.shape(a)))
b = np.shape(a)[0]
if b <= 3:
print 'ok'
I am creating a 1D numpy array (actually "a" is an input, which can be 1D or 2D). Then I reformat this to form a 2D numpy array. I am trying to use the size of a newly created dimension as a comparator and I am getting an error: "TypeError: Integer required"
I also tried "int (b)" to convert a long integer to a simple integer in an if statement and it gives the same error. If I do "type (b)" it gives me "the type is" long ". It seems to me that I have done this before without any problem, but I can’t find any examples. It’s something with the way I change 1D -array to 2D array? Any help is appreciated.
source to share
It looks like you are trying to do the same as np.atleast_2d
:
def atleast_2d(*arys): # *arys handles multiple arrays
res = []
for ary in arys:
ary = asanyarray(ary)
if len(ary.shape) == 0 :
result = ary.reshape(1, 1)
elif len(ary.shape) == 1 : # looks like your code!
result = ary[newaxis,:]
else :
result = ary
res.append(result)
if len(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 this is a list:
In [961]: np.atleast_2d([1,2,3,4])
Out[961]: array([[1, 2, 3, 4]])
you can also check the attribute ndim
:a.ndim==1
source to share