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
Creating DataFrame from dict of narray-lists in Python
Pandas is a widely used Python library for data processing and analysis. In this article, we will see how to create pandas DataFrame from Python dictionaries containing lists as values.
Creating DataFrame from Dictionary with Lists
A dictionary with lists as values can be directly converted to a DataFrame using pd.DataFrame(). Each key becomes a column name, and the corresponding list becomes the column data.
Example
Let's create a DataFrame from a dictionary containing exam schedule information ?
import pandas as pd
# Dictionary for Exam Schedule
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_schedule_df = pd.DataFrame(exam_schedule)
print(exam_schedule_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
Adding Custom Index
You can specify custom row indices when creating the DataFrame by using the index parameter. This is useful when you want meaningful row labels instead of default numeric indices.
Example
Let's create a DataFrame with custom index labels ?
import pandas as pd
# Dictionary for Exam Schedule
exam_schedule = {
'Exam Subject': ['Chemistry', 'Physics', 'Maths', 'English', 'Biology'],
'Exam Time': ['2 PM', '10 AM', '11 AM', '1 PM', '3 PM']
}
# Dictionary to DataFrame with custom index
exam_schedule_df = pd.DataFrame(exam_schedule, index=['Mon', 'Tue', 'Wed', 'Thu', 'Fri'])
print(exam_schedule_df)
Exam Subject Exam Time
Mon Chemistry 2 PM
Tue Physics 10 AM
Wed Maths 11 AM
Thu English 1 PM
Fri Biology 3 PM
Key Points
When creating DataFrames from dictionaries:
- All lists must have the same length
- Dictionary keys become column names
- List values become column data
- Custom indices can be specified using the
indexparameter
Conclusion
Creating DataFrames from dictionaries with lists is straightforward using pd.DataFrame(). You can optionally specify custom row indices for more meaningful data representation.
