Python Dictionary for Pandas Dataframe

How to convert python dictionary to pandas data frame. This is how I do it now, 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 to be the rows of the pandas data frame.

+3
source share
2 answers
 pd.DataFrame({'Keys': MyDict.keys(), 'Values': MyDict.values()}) 

returns

  Keys Values 0 key2 value2 1 key1 value1 
+5
source

If you want to use loc () to access each row in a 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 
+1
source

Source: https://habr.com/ru/post/1015292/


All Articles