Home »
Python »
Python Programs
Convert list of dictionaries to a pandas DataFrame
Given a list of dictionaries, we have to convert it into a pandas DataFrame.
Submitted by Pranit Sharma, on April 17, 2022
DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and the data. In the real world, CSV files are imported and then converted into DataFrames, but DataFrame can be created with the help of python dictionaries, lists, or a list of dictionaries. Here, we are going to see how to convert a list of dictionaries into pandas DataFrame?
pandas.DataFrame() method
To work with pandas, we need to install the pandas package. Inside pandas, we have the DataFrame() method which is used to create a DataFrame. It takes a series/sequence or dictionaries as a parameter to convert it into a Datarame.
Syntax:
pandas.DataFrame(
data=None,
index=None,
columns=None,
dtype=None,
copy=None
)
To work with Python Pandas, we need to import the pandas library. Below is the syntax,
import pandas as pd
Let us understand with the help of an example.
Example:
# Importing pandas package
import pandas as pd
# Creating a list of dictionary
data=[{'Product':'Television','Stock':300,'Production':25,'Price':20000},
{'Product':'Mobile','Stock':500,'Production':250,'Price':10000},
{'Product':'Headphones','Stock':100,'Production':20,'Price':2000}]
# Converting a list of dictionary into DataFrame
# by using pd.DataFrame method
# 'data' will be passed as a parameter inside
# DataFrame() method
df = pd.DataFrame(data)
# Display the DataFrame
print("\nDataFrame created:\n\n",df)
Output:
DataFrame created:
Price Product Production Stock
0 20000 Television 25 300
1 10000 Mobile 250 500
2 2000 Headphones 20 100
Python Pandas Programs »
ADVERTISEMENT
ADVERTISEMENT