Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of dictionaries to numpy matrix? [duplicate]

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 ?

like image 531
Tamim Addari Avatar asked Jul 03 '16 16:07

Tamim Addari


People also ask

What does .values do in Numpy?

The values property is used to get a Numpy representation of the DataFrame. Only the values in the DataFrame will be returned, the axes labels will be removed. The values of the DataFrame. A DataFrame where all columns are the same type (e.g., int64) results in an array of the same type.

Can Numpy array store dictionaries?

We can use Python's numpy. save() function from transforming an array into a binary file when saving it. This method also can be used to store the dictionary in Python.


1 Answers

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.

like image 52
John Zwinck Avatar answered Oct 06 '22 07:10

John Zwinck