Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

361
Vistas
Convert numpy.recarray to dict assigning entries to their fundamental types for passing to fastAPI

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'
)]
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda