1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Efficient way to cast scalars to NumPy arrays

Discussão em 'Python' iniciado por Stack, Novembro 21, 2025.

  1. Stack

    Stack Membro Participativo

    When I write a function that accepts ndarray or scalar inputs

    def foo(a):
    # Does something to `a`
    #
    # a: `x` dimensional array or scalar
    # . . .

    cast(a, x)
    # Deal with `a` as if it is an `x`-d array after this


    Is there an efficient way to write that cast function? Basically, I'd want a function that would cast:

    • a, a scalar to ndarray with shape ((1,)*x)
    • b, an ndarray with y<x dims explicitly to shape ((1,) * (y-x) + b.shape) (same as broadcasting)
    • c, an ndarray with x dims is unaffected
    • d, an ndarray with y>x dims throws an error
    • do it all in-place (at least when starting with an array), to prevent double memory

    It seems like this functionality is repeated so often in built-in functions that there should be some shortcut for it, but I'm not finding it.

    I can do a_ = np.array(a, ndmin = x, copy = False) and then assert len(a_.shape) == x) , but that still makes a copy of arrays. (I.e., a_.base is a is False). Is there a way around this?

    Continue reading...

Compartilhe esta Página