Numpy.array () exceptions (sorry for the originally terrible name)

I am learning Python and numpy, and I am new to duck print idea. I am writing functions in which something / someone should pass a numpy array. Trying to declare duck print, I write my code to use numpy.array with copy= and ndmin= parameters to convert arrays array_likes or 1d / 0d to the form I need. In particular, I use the ndmin= parameter in cases where I can accept either an array (p,p) or a scalar; a scalar can be encoded as an array int , (1,) , array (1,1) , [1] , etc ...

Therefore, to take care of this, I use something like S = numpy.array(S,copy=False,ndmin=2) to get the array (if possible) using the correct ndim , and then check the form as I need . I know that I have to insert this into the Try-Except block, but I can not find any documentation about what numpy.array() exception might be. So I now have this:

 # duck covariance matrix into a 2d matrix try: S = numpy.array(S, ndmin = 2, copy=False) except Exception as e: raise e 

What specific exception (s) should I try to catch here? Thanks.

+4
source share
2 answers

Document your function as receiving an array_like object and leave the exception handling to the caller.

numpy.array() is a very permissive function, it converts almost everything into an array.

+3
source

Try using np.asarray to convert inputs to arrays. He ensured that nothing was being copied if the input was already a Numpy array. If you expect to get subclasses of array , use np.asanyarray .

Note that many Numpy interfaces do not care if the input is 1 or 2-dimensional - for example, np.dot works with both 1- and 2-dimensional inputs. It's probably best to leave it that way - in this way, things like scalar multiplication just work.

0
source

Source: https://habr.com/ru/post/1435446/


All Articles