Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionary to Pandas Dataframe

Tags:

python

pandas

How do I convert a python dictionary to a pandas data frame. This is how I currently do it which is not at all elegant.

import pandas as pd
MyDict={'key1':'value1','key2' : 'value2'}
MyDF=pd.DataFrame.from_dict(MyDict,orient='index',dtype=None)
MyDF.index.name = 'Keys'
MyDF.reset_index(inplace=True)

I just want the 'key:value' pair in MyDict as the rows of a pandas dataframe.

like image 748
dineshdileep Avatar asked Jan 04 '16 10:01

dineshdileep


People also ask

How do I convert a dictionary to a DataFrame pandas?

We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.

Can Python dictionary will be converted into pandas series?

We use series() function of pandas library to convert a dictionary into series by passing the dictionary as an argument. Let's see some examples: Example 1: We pass the name of dictionary as an argument in series() function. The order of output will be same as of dictionary.

Can DataFrame be created from dictionary?

Create dataframe with Pandas DataFrame constructor The dictionary below has two keys, scene and facade. Each value has an array of four elements, so it naturally fits into what you can think of as a table with 2 columns and 4 rows. Pandas is designed to work with row and column data. Each row has a row index.


2 Answers

pd.DataFrame({'Keys': MyDict.keys(), 'Values': MyDict.values()})

returns

   Keys  Values
0  key2  value2
1  key1  value1
like image 77
eumiro Avatar answered Oct 13 '22 20:10

eumiro


If you want to use loc() to access each row in the DataFrame by key then

MyDF = pd.DataFrame([v for v in MyDict.values()], columns = ['value'],
                    index = [k for k in MyDict.keys()])

MyDF then contains

       value
key2  value2
key1  value1

and

MyDF.loc['key2'].value

returns

value2
like image 24
SpeedCoder5 Avatar answered Oct 13 '22 21:10

SpeedCoder5