The Wayback Machine - https://web.archive.org/web/20240913190431/https://www.geeksforgeeks.org/create-a-pandas-dataframe-from-list-of-dicts/
Open In App

Create a Pandas DataFrame from List of Dicts

Last Updated : 26 Mar, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pandas DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. It is generally the most commonly used Pandas object. Pandas DataFrame can be created in multiple ways using Python. Let’s discuss how to create a Pandas DataFrame from the List of Dictionaries.

Create a Pandas DataFrame from List of Dictionaries

Below are the ways by which we can create a Pandas DataFrame from list of dicts:

  • Using from_records()
  • Using pd.DataFrame.from_dict()
  • Using pd.json_normalize
  • Using pd.DataFrame

Create a Pandas DataFrame from List of Dictionaries Using from_records()

Pandas from_records() function of DataFrame changes structured data or records into DataFrames. It converts a structured ndarray, tuple or dict sequence, or DataFrame into a DataFrame object.

Python3




import pandas as pd 
    
# Initialise data to lists. 
data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},
        {'Geeks':10, 'For': 20, 'geeks': 30}] 
  
df = pd.DataFrame.from_records(data,index=['1', '2'])
print(df)


Output

       Geeks    For geeks
1 dataframe using list
2 10 20 30

Convert List of Dictionaries to a Pandas DataFrame Using pd.DataFrame.from_dict()

The DataFrame.from dict() method in Pandas builds DataFrame from a dictionary of the dict or array type. By using the dictionary’s columns or indexes and allowing for Dtype declaration, it builds a DataFrame object.

Python3




import pandas as pd 
    
# Initialise data to lists. 
data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},
        {'Geeks':10, 'For': 20, 'geeks': 30}] 
  
df = pd.DataFrame.from_dict(data)
print(df)


Output

       Geeks    For geeks
0 dataframe using list
1 10 20 30

Create a Pandas DataFrame from List of Dictionaries Using pd.json_normalize

Pandas have a nice inbuilt function called json_normalize() to flatten the simple to moderately semi-structured nested JSON structures to flat tables.

Python3




import pandas as pd 
    
# Initialise data to lists. 
data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},
        {'Geeks':10, 'For': 20, 'geeks': 30}] 
  
df=pd.json_normalize(data)
print(df)


Output

       Geeks    For geeks
0 dataframe using list
1 10 20 30

Convert List of Dictionaries to a Pandas DataFrame Using pd.DataFrame

Example 1: As we know while creating a data frame from the dictionary, the keys will be the columns in the resulted Dataframe. When we create Dataframe from a list of dictionaries, matching keys will be the columns and corresponding values will be the rows of the Dataframe. If there are no matching values and columns in the dictionary, then the NaN value will be inserted into the resulting Dataframe.

Python3




# Python code demonstrate how to create  
# Pandas DataFrame by lists of dicts without matching key-value pair 
import pandas as pd 
    
# Initialise data to lists. 
data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list', 'Portal': 10000},
        {'Geeks':10, 'For': 20, 'geeks': 30}] 
    
# Creates DataFrame. 
df = pd.DataFrame(data) 
    
# Print the data 
df


Output

       Geeks    For geeks   Portal
0 dataframe using list 10000.0
1 10 20 30 NaN

Example 2: Creating a Dataframe by explicitly providing user-defined values for both index and columns 

Python3




import pandas as pd
  
# Initialise data to lists.
data = [{'Geeks': 'dataframe', 'For': 'using', 'geeks': 'list'},
        {'Geeks': 10, 'For': 20, 'geeks': 30}]
  
# With two column indices, values same
# as dictionary keys
df1 = pd.DataFrame(data, index=['ind1', 'ind2'],
                   columns=['Geeks', 'For'])
  
# With two column indices with
# one index with other name
df2 = pd.DataFrame(data, index=['indx', 'indy'])
  
# print for first data frame
print(df1, "\n")
  
# Print for second DataFrame.
print(df2)


Output

          Geeks    For
ind1 dataframe using
ind2 10 20
Geeks For geeks
indx dataframe using list
indy 10 20 30


Previous Article
Next Article

Similar Reads

Python | Removing duplicate dicts in list
Removal of duplicates is essential in many applications. A list of dictionaries is quite common and sometimes we require to duplicate the duplicated. Let's discuss certain ways in which we can remove duplicate dictionaries in a list in Python. Using Loop for Removing duplicate dictionaries in a listThe basic method that comes to our mind while perf
4 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Create a list from rows in Pandas DataFrame | Set 2
In an earlier post, we had discussed some approaches to extract the rows of the dataframe as a Python's list. In this post, we will see some more methods to achieve that goal. Note : For link to the CSV file used in the code, click here. Solution #1: In order to access the data of each row of the Pandas dataframe, we can use DataFrame.iloc attribut
2 min read
Create a list from rows in Pandas dataframe
Python list is easy to work with and also list has a lot of in-built functions to do a whole lot of operations on lists. Pandas dataframe's columns consist of series but unlike the columns, Pandas dataframe rows are not having any similar association. In this post, we are going to discuss several ways in which we can extract the whole row of the da
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Create a SQL table from Pandas dataframe using SQLAlchemy
In this article, we will discuss how to create a SQL table from Pandas dataframe using SQLAlchemy. As the first steps establish a connection with your existing database, using the create_engine() function of SQLAlchemy. Syntax: from sqlalchemy import create_engine engine = create_engine(dialect+driver://username:password@host:port/database) Explana
3 min read
Create pandas dataframe from lists using zip
One of the way to create Pandas DataFrame is by using zip() function. You can use the lists to create lists of tuples and create a dictionary from it. Then, this dictionary can be used to construct a dataframe. zip() function creates the objects and that can be used to produce single item at a time. This function can create pandas DataFrames by mer
2 min read
Python | Create a Pandas Dataframe from a dict of equal length lists
Given a dictionary of equal length lists, task is to create a Pandas DataFrame from it. There are various ways of creating a DataFrame in Pandas. One way is to convert a dictionary containing lists of equal lengths as values. Let's discuss how to create a Pandas Dataframe from a dict of equal length lists with help of examples. Example #1: Given a
2 min read
Create pandas dataframe from lists using dictionary
Pandas DataFrame is a 2-dimensional labeled data structure like any table with rows and columns. The size and values of the dataframe are mutable, i.e., can be modified. It is the most commonly used pandas object. Creating pandas data-frame from lists using dictionary can be achieved in multiple ways. Let’s discuss different ways to create a DataFr
2 min read
Create a column using for loop in Pandas Dataframe
Adding a new column in an already created dataframe is quite easy. Adding a new column is actually required to process the data of dataframe created earlier. For that purpose, we can process the existing data and make a separate column to store the data. The simplest way to add a new column along with data is by creating a new column and assigning
3 min read
Ways to Create NaN Values in Pandas DataFrame
Let's discuss ways of creating NaN values in the Pandas Dataframe. There are various ways to create NaN values in Pandas dataFrame. Those are: Using NumPy Importing csv file having blank values Applying to_numeric function Method 1: Using NumPy C/C++ Code import pandas as pd import numpy as np num = {'number': [1,2,np.nan,6,7,np.nan,np.nan]} df = p
1 min read
Create empty dataframe in Pandas
The Pandas Dataframe is a structure that has data in the 2D format and labels with it. DataFrames are widely used in data science, machine learning, and other such places. DataFrames are the same as SQL tables or Excel sheets but these are faster in use.Empty DataFrame could be created with the help of pandas.DataFrame() as shown in below example:
1 min read
Create a Pandas DataFrame from a Numpy array and specify the index column and column headers
This article demonstrates multiple examples to convert the Numpy arrays into Pandas Dataframe and to specify the index column and column headers for the data frame. Example 1: In this example, the Pandas dataframe will be generated and proper names of index column and column headers are mentioned in the function. This approach can be used when ther
4 min read
How to create Pandas DataFrame from nested XML?
In this article, we will learn how to create Pandas DataFrame from nested XML. We will use the xml.etree.ElementTree module, which is a built-in module in Python for parsing or reading information from the XML file. The ElementTree represents the XML document as a tree and the Element represents only a single node of the tree. Functions Used: Here,
3 min read
Create Pandas Dataframe from Dictionary of Dictionaries
In this article, we will discuss how to create a pandas dataframe from the dictionary of dictionaries in Python. Method 1: Using DataFrame() We can create a dataframe using Pandas.DataFrame() method. Syntax: pandas.DataFrame(dictionary) where pandas are the module that supports DataFrame data structureDataFrame is the datastructure that converts di
2 min read
How to Create Pie Chart from Pandas DataFrame?
In this article, we will discuss how to create a Pie chart from Pandas dataframe using Python. The data in a circular graph is represented by a pie chart, which is a form of a graph. In research, engineering, and business, it is frequently utilized. The segments of the pie depict the data's relative strength and are a sort of graphical representati
4 min read
How to Create Boxplot from Pandas DataFrame?
Box plot is also called a Whisker plot which provides a summary of a set of data that includes minimum, first-quartile, median, third quartile, and maximum value. This Box plot is present in the matplotlib library. In the Box plot graph, the x-axis represents the data we are going to plot and the y-axis represents frequency. Method 1: Using DataFra
3 min read
How to Create a Histogram from Pandas DataFrame?
A histogram is a graph that displays the frequency of values in a metric variable's intervals. These intervals are referred to as "bins," and they are all the same width. We can create a histogram from the panda's data frame using the df.hist() function. Syntax: DataFrame.hist(column=None, by=None, grid=True, xlabelsize=None, xrot=None, ylabelsize=
2 min read