-->

Monday, July 20, 2015

Turn a {key, value} Python Dictionary into a Pandas DataFrame

Quick solution to a problem I had today. I had a dictionary of {key, values} that I wanted into a dataframe. My solution:

import pandas as pd
pd.DataFrame([[key,value] for key,value in python_dict.iteritems()],columns=["key_col","val_col"])

4 comments:

  1. why do you want to do that when it can be done directly as :
    l = [{k1:v11, k2:v21},
    {k1:v21, k2:v22}, .....]

    pd.DataFreame(l)

    ReplyDelete
    Replies
    1. That only works if you already have a list. My usecase was when I only had a single dictionary full of keys and values. You have to make it a list first.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Would it be easier to use pd.Series(python_dict).to_frame()

    ReplyDelete