Tamim Ad Dari Tamim Ad Dari - 5 months ago 9
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

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

import pandas as pd
pd.DataFrame(d).values

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.