Pandas Tutorial – Create Pandas DataFrame from dictionary.

Spread the love

You have some data in a python dictionary and you want convert them into a pandas dataframe for analysis. For example, you have some restaurant data in a python dictionary and we want to create a dataframe like this.

Solution –

Method 1 –

To create a pandas dataframe from a dict, we can directly pass the dictionary to the pandas dataframe constructor pd.DataFrame. By default, the dictionary keys will be the name of the columns in the dataframe.

let’s first create the dictionary.

data = {'Restaurant': [1, 2, 3, 4, 5],
       'Quality rating': ['Good','Very Good','Good','Excellent','Very Good'],
       'Meal price ($)': [18, 22, 28, 38, 33]}

Now, to create a pandas dataframe, we can just pass this data to the pd.DataFrame.

# import pandas
import pandas as pd

# create dataframe from dict
df = pd.DataFrame(data)

If you want you can also change the index and columns of this dataframe using the index and column parameters of the dataframe constructor. Please read this post to know how – Create Pandas DataFrame from Lists.

Method 2 –

There is one another method of creating a dataframe from a dictionary using pd.DataFrame.from_dict in pandas which gives you more control on how you create the dataframe.

df = pd.DataFrame.from_dict(data)

pd.DataFrame.from_dict method also has an orient parameter that let’s you decide the orientation of your data. By Default the orient=’columns’ means the dictionary keys will be used for creating the column names.

df = pd.DataFrame.from_dict(data, orient='columns')

If you want to use the dictionary keys as the index of the dataframe then pass orient=’index’ .

df = pd.DataFrame.from_dict(data, orient='index')

You can also change the column names using the columns parameter.

df = pd.DataFrame.from_dict(data, orient='index', columns=['A','B','C','D','E'])

  1. How to Create Pandas DataFrame from Lists and List of Lists.
  2. Convert a Pandas DataFrame to a Dictionary.
  3. Create a Pandas Series from a list.

Rating: 1 out of 5.

Leave a Reply