Is there a more concise way to assign values to structured arrays?

In this script:

import numpy as np, numba as nb

@nb.njit
def f(a):
  for i in range(len(a)):
    # a[i] = (i, i+1)  works with Python, but not Numba
    a[i]['x'] = i
    a[i]['y'] = i+1

Point = np.dtype([('x', 'f4'), ('y', 'f4')])
a = np.empty((10,), dtype=Point)
f(a)
print(a)

I have to assign values to each field of a structured array record individually, as opposed to bulk assignment with a tuple. Is there a more concise way, which works with Numba?

@pauljurczak if your structured array has homogenous fields you could write to a view of the array.


import numpy as np
import numba as nb

@nb.njit
def f(av):
    for i in range(len(a)):
        av[i] = [i, i+1]

Point = np.dtype([('x', 'f4'), ('y', 'f4')])
a = np.empty((10,), dtype=Point)
av = a.view(dtype=np.dtype((np.float32, 2)))
f(av)
print(a)
# [(0.,  1.) (1.,  2.) (2.,  3.) (3.,  4.) (4.,  5.) (5.,  6.) (6.,  7.)
#  (7.,  8.) (8.,  9.) (9., 10.)]
1 Like

Unfortunately, I oversimplified my example. The real use case has a mix of f4 and i4 fields.