ADVERTISEMENT
ADVERTISEMENT

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
Convert list of dictionaries to a pandas DataFrame | Output

Python Pandas Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.