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.
We can convert a dictionary to a pandas dataframe by using the pd. DataFrame. from_dict() class-method.
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.
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.
pd.DataFrame({'Keys': MyDict.keys(), 'Values': MyDict.values()})
returns
Keys Values
0 key2 value2
1 key1 value1
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With