Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Create a Pandas Dataframe from a dict of equal length lists in Python
A Pandas DataFrame can be created from a dictionary where values are lists of equal length. This approach is useful when you have related data stored in separate lists and want to combine them into a tabular structure.
Using Separate Lists and Dictionary
In this approach, we declare lists individually and then use each list as a value for the appropriate key inside a dictionary. Finally, we apply pd.DataFrame() to convert the dictionary into a DataFrame ?
Example
import pandas as pd
# Lists for Exam schedule
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
subjects = ['Chemistry', 'Physics', 'Maths', 'English', 'Biology']
times = ['2 PM', '10 AM', '11 AM', '1 PM', '3 PM']
# Dictionary for Exam Schedule
exam_schedule = {'Exam Day': days,
'Exam Subject': subjects,
'Exam Time': times}
# Dictionary to DataFrame
exam_df = pd.DataFrame(exam_schedule)
print(exam_df)
Exam Day Exam Subject Exam Time 0 Mon Chemistry 2 PM 1 Tue Physics 10 AM 2 Wed Maths 11 AM 3 Thu English 1 PM 4 Fri Biology 3 PM
Using Lists Directly in Dictionary
In this approach, we define lists directly as values inside the dictionary instead of declaring them separately. This method is more concise and creates the DataFrame in fewer lines of code ?
Example
import pandas as pd
# Dictionary with lists as values
exam_schedule = {
'Exam Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
'Exam Subject': ['Chemistry', 'Physics', 'Maths', 'English', 'Biology'],
'Exam Time': ['2 PM', '10 AM', '11 AM', '1 PM', '3 PM']
}
# Dictionary to DataFrame
exam_df = pd.DataFrame(exam_schedule)
print(exam_df)
Exam Day Exam Subject Exam Time 0 Mon Chemistry 2 PM 1 Tue Physics 10 AM 2 Wed Maths 11 AM 3 Thu English 1 PM 4 Fri Biology 3 PM
Key Requirements
When creating a DataFrame from a dictionary of lists, ensure that:
- Equal length − All lists must have the same number of elements
- Dictionary keys become column names in the DataFrame
- List values become the data in each column
- Index is automatically generated starting from 0
Conclusion
Both methods create DataFrames from dictionaries with equal-length lists. Use separate lists when you need to reuse them elsewhere, or define lists directly in the dictionary for more concise code.
