Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

How to convert an xml file to pandas dataframe?

1 Answer

0 votes
by (25.1k points)

Unfortunately there is no method in pandas library convert xml file to a dataframe easily. So, you need to do it yourself. You can do it by using the etree module in python.

You would need to firstly parse an XML file and create a list of columns for data frame. then extract useful information from the XML file and add to a pandas data frame.

Here is a sample code that you can use.:

import pandas as pd 

import xml.etree.ElementTree as etree

tree = etree.parse("employee.xml")

root = tree.getroot()

columns = ["name", "email", "age"]

datatframe = pd.DataFrame(columns = columns)

for node in root: 

    name = node.attrib.get("name")

    mail = node.find("email").text if node is not None else None

    age = node.find("age").text if node is not None else None

    datatframe = datatframe.append(pd.Series([name, mail, age], index = columns), ignore_index = True)

In case you wish to learn more about pandas you can take a look at this video:

If you wish to learn more about Python, visit the Python tutorial and Python course by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Dec 6, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...