Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

360
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!