Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

362
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda