[Python] How to create a NumPy structured array with different field values using full_like?

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    I would like to create a NumPy structured array b with the same shape as a and (-1, 1) values, for example:

    import numpy as np

    Point = [('x', 'i4'), ('y', 'i4')]
    a = np.zeros((4, 4), dtype='u1')
    b = np.full_like(a, fill_value=(-1, 1), dtype=Point) # fails
    b = np.full_like(a, -1, dtype=Point) # works


    Using full_like() works with the same value for all fields, but fails with different values, producing this error:

    multiarray.copyto(res, fill_value, casting='unsafe')
    ValueError: could not broadcast input array from shape (2,) into shape (4,4)


    . Is there a solution other than explicitly assigning (-1, 1) to each element in a loop?

    Continue reading...

Compartilhe esta Página