pythonnumpystructured-array

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


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?


Solution

  • Convert the fill value into an array with the Point dtype as well

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

    Alternatively, if you don't need a, just create the array directly with your desired shape

    import numpy as np
    
    Point = [('x', 'i4'), ('y', 'i4')]
    b = np.full((4, 4), np.array((-1, 1), dtype=Point))