The Wayback Machine - https://web.archive.org/web/20240606122053/https://www.geeksforgeeks.org/how-to-create-pandas-dataframe-from-nested-xml/
Open In App

How to create Pandas DataFrame from nested XML?

Last Updated : 28 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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, we will use some functions to process out code which is stated below:

  • ElementTree.parse( XML_file) : To read data from an XML file
  • root.iter(‘root_name’): To iterate through the branches of the root node
  • ElementTree.fromstring(XML_file) : To read data when XML code which is passed as a string inside triple quotes in the python code
  • prstree.findall(‘store’): To find all the elements of the parsed XML ElementTree
  • node.attribute.get(attribte_name ): To get the attribute
  • node.find(attribte_name): To retrieve the text content of the mentioned attribute_name
  • pandas.DataFrame() : To convert the XML data to a DataFrame
  • list.append(): To append the items to a list

Approach

  • Parse or read the XML file using ElementTree.parse( ) function and get the root element.
  • Iterate through the root node to get the child nodes attributes ‘SL NO’ (here) and extract the text values of each attribute (here foodItem, price, quantity, and discount).
  • Get the respective food items with specifications as a unit appended to a list(here all_items() list).
  • Convert the list into a DataFrame using pandas.DataFrame() function and mention the column names within quotes separated by commas.
  • Print the DataFrame and it’s done.

Input Nested XML Data

XML




<?xml version="1.0" encoding="UTF-8"?>
  
       <Food>
  
           <Info>
           <Msg>Food Store items.</Msg>
           </Info>
  
           <store slNo="1">
               <foodItem>meat</foodItem>
               <price>200</price>
               <quantity>1kg</quantity>
               <discount>7%</discount>
           </store>
  
           <store slNo="2">
               <foodItem>fish</foodItem>
               <price>150</price>
               <quantity>1kg</quantity>
               <discount>5%</discount>
           </store>
  
           <store slNo="3">
               <foodItem>egg</foodItem>
               <price>100</price>
               <quantity>50 pieces</quantity>
               <discount>5%</discount>
           </store>
  
           <store slNo="4">
               <foodItem>milk</foodItem>
               <price>50</price>
               <quantity>1 litre</quantity>
               <discount>3%</discount>
           </store>
  
       </Food>


Example 1:

In this code below we have parsed the XML file. Give the complete path where you have saved the XML file within quotes. So here we need to use ElementTree.parse() function to read the data from the XML file and then the getroot() function to get the root. Then follow the steps given.

Python3




import xml.etree.ElementTree as ETree
import pandas as pd
  
# give the path where you saved the xml file
# inside the quotes
xmldata = "C: \\ProgramData\\Microsoft\\
    Windows\\Start Menu\\Programs\\
    Anaconda3(64-bit)\\xmltopandas.xml"
prstree = ETree.parse(xmldata)
root = prstree.getroot()
  
# print(root)
store_items = []
all_items = []
  
for storeno in root.iter('store'):
    
    store_Nr = storeno.attrib.get('slNo')
    itemsF = storeno.find('foodItem').text
    price = storeno.find('price').text
    quan = storeno.find('quantity').text
    dis = storeno.find('discount').text
  
    store_items = [store_Nr, itemsF, price, quan, dis]
    all_items.append(store_items)
  
xmlToDf = pd.DataFrame(all_items, columns=[
  'SL No', 'ITEM_NUMBER', 'PRICE', 'QUANTITY', 'DISCOUNT'])
  
print(xmlToDf.to_string(index=False))


Output:

Note: The XML file should be saved in the same directory or folder where your Python code saved.

Example 2:

We can also pass the XML content as a string inside triple quotes. In that case, we need to use the fromstring() function to read the string. Get the root using the ‘tag’ object and follow the same steps to convert it to a DataFrame as mentioned above.

Python3




import xml.etree.ElementTree as ETree
import pandas as pd
  
xmldata = '''<?xml version="1.0" encoding="UTF-8"?>
        <Food>
            <Info>
            <Msg>Food Store items.</Msg>
            </Info>
            <store slNo="1">
                <foodItem>meat</foodItem>
                <price>200</price>
                <quantity>1kg</quantity>
                <discount>7%</discount>
            </store>
            <store slNo="2">
                <foodItem>fish</foodItem>
                <price>150</price>
                <quantity>1kg</quantity>
                <discount>5%</discount>
            </store>
            <store slNo="3">
                <foodItem>egg</foodItem>
                <price>100</price>
                <quantity>50 pieces</quantity>
                <discount>5%</discount>
            </store>
            <store slNo="4">
                <foodItem>milk</foodItem>
                <price>50</price>
                <quantity>1 litre</quantity>
                <discount>3%</discount>
            </store>
        </Food>
'''
  
prstree = ETree.fromstring(xmldata)
root = prstree.tag
  
#print(root)
store_items = []
all_items = []
  
for storeno in prstree.findall('store'):  
    store_Nr = storeno.attrib.get('slNo')
    itemsF= storeno.find('foodItem').text
    price= storeno.find('price').text
    quan= storeno.find('quantity').text
    dis= storeno.find('discount').text
          
    store_items = [store_Nr,itemsF,price,quan,dis]
    all_items.append(store_items)
  
xmlToDf = pd.DataFrame(all_items,columns=[
  'SL No','ITEM_NUMBER','PRICE','QUANTITY','DISCOUNT'])        
  
print(xmlToDf.to_string(index=False))


Output:



Similar Reads

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
2 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
Python | Convert list of nested dictionary into Pandas dataframe
Given a list of the nested dictionary, write a Python program to create a Pandas dataframe using it. We can convert list of nested dictionary into Pandas DataFrame. Let's understand the stepwise procedure to create a Pandas Dataframe using the list of nested dictionary. Convert Nested List of Dictionary into Pandas DataframeBelow are the methods th
4 min read
Normalizing Nested Json Object Into Pandas Dataframe
The encapsulation of one or more JSON objects into another JSON object is called a nested JSON object. There are various circumstances when we have the data in JSON object form and have to imply numerous functions on the dataset. In such cases, we can use the Python library called Pandas which is used for datasets. For converting into a Pandas data
3 min read
Python Pandas Dataframe To Nested Json
When working with data in Python,Pandas is a popular library for handling tabular data efficiently. Converting a Pandas DataFrame to a nested JSON structure can be necessary for various reasons, such as preparing data for API responses or interacting with nested JSON-based data structures. In this article, we will explore four approaches to achievi
3 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
Practice Tags :