[Python] turn Python float argument into numpy array, keep array argument the same

Discussão em 'Python' iniciado por Stack, Setembro 4, 2025.

  1. Stack

    Stack Membro Participativo

    I have a simple function that is math-like:

    def y(x):
    return x**2


    I know the operation x**2 will return a numpy array if supplied a numpy array and a float if supplied a float.

    for more complicated functions that include an integral I want it to return a numpy array in all cases, even if supplied a float. I designed my function like this to handle the array case. NOTE: the integrate.quad function I don't believe is vectorized natively and I'm weary of using np.vectorize even if it works because I (think) I've seen major performance degradation before.

    def f(x):
    out = np.zeros(np.shape(x))
    for i,X in enumerate(X):
    out = scipy.integrate.quad(y,0,5)[0]

    return out



    I have often used an if statement like:

    if ~isinstance(t,np.ndarray):
    t = np.asarray([t])


    I wonder if there is a more efficient way. Is there a one-liner? Can I add checking that the input is not something ridiculous like a string too in an elegant and understandable way?

    Continue reading...

Compartilhe esta Página