3

I have a function, processing a 1D numpy array, like this:

def f(arr):
 arr=asarray(arr)
 #process data as numpy array
 #...
 return arr

With asarray I allow to call the function with a list as f([4,5,6]). Now, I would like to "overload" the argument also to a single float, so that I can use f(4) instead of f([4]).

This is a standard numpy feature, since you can call np.sin as sin(array([4,5,6])), or as sin([4,5,6]) or as sin(4) as well. I came up with this code, that works at least in simple cases:

def f(arr):
 arr=asarray(arr)
 if arr.shape is ():
 print 'arr is a single float/int/etc'
 arr = array([arr])
 #process data as numpy array
 #...
 return arr

Is this the standard/correct way to do it?

asked Sep 13, 2013 at 11:28
0

1 Answer 1

2

I believe you are looking for np.atleast_1d.

>>> np.atleast_1d(5)
array([5])
>>> np.atleast_1d(np.arange(2))
array([0, 1])
answered Sep 13, 2013 at 12:07
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.