How to Create a Pandas Dataframe From a List of Dictionaries in Python
Creating a DataFrame from a list of dictionaries is a common task in data analysis. In Python, you can easily accomplish this using the DataFrame()
function from the pandas library.
The following example shows how to create a dataframe from a list of dictionaries in Python.
Using DataFrame() Function
The DataFrame()
function is a powerful tool in pandas that lets you convert various data structures, including lists of dictionaries, into a structured table (DataFrame).
Each dictionary in the list corresponds to a row in the resulting DataFrame, with dictionary keys becoming the column names.
Let’s say you have a list of product details, and you want to create a DataFrame from this data. Here’s how to do it:
# Import pandas library
import pandas as pd
# Create a list of dictionaries
data = [
{"Date": "01-03-2023", "Product_Code": "A-101", "Product_Name": "Laptop", "Price": 4500, "Status": 1},
{"Date": "01-03-2023", "Product_Code": "A-102", "Product_Name": "Mobile", "Price": 550, "Status": 1},
{"Date": "01-03-2023", "Product_Code": "A-103", "Product_Name": "Printer", "Price": 250, "Status": 1},
{"Date": "01-03-2023", "Product_Code": "B-101", "Product_Name": "Keyboard", "Price": 50, "Status": 0},
{"Date": "02-03-2023", "Product_Code": "B-102", "Product_Name": "Scanner", "Price": 350, "Status": 1},
{"Date": "02-03-2023", "Product_Code": "B-104", "Product_Name": "Mouse", "Price": 50, "Status": 1},
]
# Create a pandas dataframe from the list of dictionaries
df = pd.DataFrame(data)
# Print the dataframe
print(df)
Output: 👇️
Date Product_Code Product_Name Price Status
0 01-03-2023 A-101 Laptop 4500 1
1 01-03-2023 A-102 Mobile 550 1
2 01-03-2023 A-103 Printer 250 1
3 01-03-2023 B-101 Keyboard 50 0
4 02-03-2023 B-102 Scanner 350 1
5 02-03-2023 B-104 Mouse 50 1
In this example:
data
: The list of dictionaries, where each dictionary represents a row of data.pd.DataFrame()
: This function takes the list and transforms it into a DataFrame, automatically assigning column names based on the dictionary keys.df
: The new DataFrame, which now holds the data in a structured format.
The output shows the dataframe created from the list of dictionaries.
Conclusion
Using the DataFrame()
function in pandas, you can easily convert a list of dictionaries into a DataFrame.
This method is great for quickly organizing your data into a usable form for analysis, allowing you to manipulate and explore your dataset with ease.