to pass the content of this recarray to fastAPI:
import numpy
rec_array = numpy.recarray(shape = (1, ),
dtype = [('col_a', 'O'),
('col_b', '<f8'),
('col_c', '<i8')])
rec_array['col_a'][0] = '0'
rec_array['col_b'][0] = 1.0
rec_array['col_c'][0] = 128
This version works:
{'col_a':[str(rec_array['col_a'][0])],
'col_b':[float(rec_array['col_b'][0])],
'col_c':[int(rec_array['col_c'][0])]}
but this one does not:
{name:[rec_array[name][0]] for name in rec_array.dtype.names}
I would like to understand why. Here is the error trace I get from fastAPI, under windows:
File "C:\Users\xor\AppData\Local\Programs\Python\Python38-32\lib\site-packages\fastapi\encoders.py", line 158, in json
able_encoder
raise ValueError(errors)
ValueError: [TypeError("'numpy.int64' object is not iterable"), TypeError('vars() argument must have __dict__ attribute'
)]
The issue you're facing is because of the int64 (<i8) type. In your first code snippet, you're explicitly casting it to a regular int:
'col_c':[int(rec_array['col_c'][0])]
===
While in the second, it stays a numpy.int64:
d = {name:[rec_array[name][0]] for name in rec_array.dtype.names}
type(d["col_c"][0])
===> numpy.int64
To solve this, you can do the following:
def make_int(x):
if isinstance(x, np.int64):
return int(x)
return x
{name:[make_int(rec_array[name][0])] for name in rec_array.dtype.names}
This results in a duct you can send to fast API.