Tamim Ad Dari Tamim Ad Dari - 1 year ago 79
Python Question

Convert a list of dictionaries to numpy matrix?

Let the given dictionaries are

d = [{'a':1,'b':4},{'b':2}]

So basically I want a matrix like this

| 'a' | 'b' |
| 1 | 4 |
| na | 2 |

How can I efficiently achieve this ?

Answer Source

The Pandas DataFrame constructor will immediately give you the result you are looking for:

import pandas as pd

The .values part on the end converts the result to a NumPy array, which is what you asked for. Some people would just work directly with the DataFrame instead.

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