将 numpy.recarray 转换为字典,将条目分配给它们的基本类型以传递给 fastAPI
Convert numpy.recarray to dict assigning entries to their fundamental types for passing to fastAPI
将此重新排列的内容传递给 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
此版本有效:
{'col_a':[str(rec_array['col_a'][0])],
'col_b':[float(rec_array['col_b'][0])],
'col_c':[int(rec_array['col_c'][0])]}
但是这个 不是:
{name:[rec_array[name][0]] for name in rec_array.dtype.names}
我想明白为什么。这是我从 fastAPI 获得的错误跟踪,在 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'
)]
您遇到的问题是因为 int64 (<i8
) 类型。在您的第一个代码片段中,您明确地将其转换为常规 int:
'col_c':[int(rec_array['col_c'][0])]
===
而在第二个中,它保持 numpy.int64
:
d = {name:[rec_array[name][0]] for name in rec_array.dtype.names}
type(d["col_c"][0])
===> numpy.int64
要解决此问题,您可以执行以下操作:
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}
这会产生一个管道,您可以快速发送 API。
将此重新排列的内容传递给 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
此版本有效:
{'col_a':[str(rec_array['col_a'][0])],
'col_b':[float(rec_array['col_b'][0])],
'col_c':[int(rec_array['col_c'][0])]}
但是这个 不是:
{name:[rec_array[name][0]] for name in rec_array.dtype.names}
我想明白为什么。这是我从 fastAPI 获得的错误跟踪,在 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'
)]
您遇到的问题是因为 int64 (<i8
) 类型。在您的第一个代码片段中,您明确地将其转换为常规 int:
'col_c':[int(rec_array['col_c'][0])]
===
而在第二个中,它保持 numpy.int64
:
d = {name:[rec_array[name][0]] for name in rec_array.dtype.names}
type(d["col_c"][0])
===> numpy.int64
要解决此问题,您可以执行以下操作:
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}
这会产生一个管道,您可以快速发送 API。