[Python] 0-dimensional array problems with `numpy.vectorize`

Discussão em 'Python' iniciado por Stack, Fevereiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    numpy.vectorize conveniently converts a scalar function to vectorized functions that can be applied directly to arrays. However, when inputting a single value into the vectorized function, the output is a 0-dimentional array instead of the corresponding value type, which can cause errors when using the result elsewhere due to typing issues. My question is: is there a mechanism in numpy that can resolve this problem by automatically convert the 0-dimensional array return value to the corresponding data type?

    For explanation I'd give an example:

    @np.vectorize ( excluded = ( 1, 2 ) )
    def rescale (
    value: float,
    srcRange: tuple [ float, float ],
    dstRange: tuple [ float, float ] = ( 0, 1 ),
    ) -> float:
    srcMin, srcMax = srcRange
    dstMin, dstMax = dstRange
    t = ( value - srcMin ) / ( srcMax - srcMin )
    return dstMin + t * ( dstMax - dstMin )


    When calling the function above with rescale ( 5, ( 0, 10 ) ) the return value is numpy.array(0.5) instead of just the value 0.5.

    Currently I resolve this problem by a self-defined decorator:

    def vectorize0dFix ( func ):
    def _func ( *args, **kwargs ):
    result = func ( *args, **kwargs )
    if isinstance ( result, np.ndarray ) and result.shape == ( ):
    return result.item ( )
    else:
    return result
    return _func


    But if this problem do causes trouble there should be a mechanism in numpy which properly deals with the problem. I wonder whether there is one or why there isn't.

    Continue reading...

Compartilhe esta Página