saloua saloua - 2 years ago 111
Python Question

Create a Record array from a list of dictionaries

Given a list of dictionaries as follows:

dict_data = [
{'name': 'r1', 'interval': [1800.0, 1900.0], 'bool_condition': [True, False]},
{'name': 'r2', 'interval': [1600.0, 1500.0], 'bool_condition': [False]},
{'name': 'r3', 'interval': [1400.0, 1600.0], 'bool_condition': [True]}

I would like to create a record array from the dictionaries data.
But when I try the following I get

import numpy as np
dt = np.dtype([
('name', np.str_, 50), ('interval', np.float64, (2,)),
('bool_condition', np.bool)
values = [tuple(val.values()) for val in dict_data]
arr = np.rec.array(values, dtype=dt)

ValueError: cannot set an array element with a sequence

I would like to know how could I have a more correct
and then create the record array from the list of dictionaries.

Answer Source

It's very convenient to do that with pandas :

 In [247]: pd.DataFrame(dict_data)[['name','interval','bool_condition']].to_records(False)

rec.array([('r1', [1800.0, 1900.0], [True, False]),
 ('r2', [1600.0, 1500.0], [False]), ('r3', [1400.0, 1600.0], [True])], 
          dtype=[('name', 'O'), ('interval', 'O'), ('bool_condition', 'O')])

['name','interval','bool_condition'] ensure the order of the fields.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download