Creating DataFrame from dict of narray-lists in Python


Pandas is a very widely used python library for data processing and data analysis. In this article we will see how we we can create pandas dataframe from given python dictionaries and lists.

From dictionary with lists

Dictionaries are key value pairs. If we take a python dictionary which has key and a list as a value then we can directly use the DataFrame method on the given dictionary to create the pandas data frame.

Example

 Live Demo

import pandas as pd

# Dictionary for Exam Schedule
Exam_Schedule = {
'Exam Day': ['Mon', 'Tue', 'Wed','Thu', 'Fri'],
'Exam Subject': ['Chemisry','Physics','Maths','English','Biology'],
'Exam Time': ['2 PM', '10 AM', '11 AM','1 PM', '3 PM']
}

# Dictionary to DataFrame
Exam_Schedule_df = pd.DataFrame(Exam_Schedule)

print(Exam_Schedule_df)

Output

Running the above code gives us the following result −

   Exam Day   Exam Subject  Time
0   Mon       Chemisry     2 PM
1   Tue       Physics     10 AM
2   Wed       Maths       10 AM
3   Thu       English      2 PM
4   Fri       Biology     10 AM

Adding index

If the data frame is already created, we can add another column to it by adding an index to it. In the below example we take the python dictionary which has exam subjects and exam time. Later we add the exam days as an index to the given data frame.

Example

 Live Demo

import pandas as pd

# Dictionary for Exam Schedule
Exam_Schedule = {
'Exam Subject': ['Chemisry','Physics','Maths','English','Biology'],
'Exam Time': ['2 PM', '10 AM', '11 AM','1 PM', '3 PM']
}

# Dictionary to DataFrame
Exam_Schedule_df = pd.DataFrame(Exam_Schedule, index = ['Mon', 'Tue', 'Wed','Thu', 'Fri'])

print(Exam_Schedule_df)

Output

Running the above code gives us the following result −

   Exam Day Exam Subject Time
0   Mon     Chemisry     2 PM
1   Tue     Physics     10 AM
2   Wed     Maths       10 AM
3   Thu     English      2 PM
4   Fri     Biology     10 AM

Updated on: 26-Aug-2020

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements