Predictive Hacks

Convert a Pandas Dataframe to XML

There is no Pandas function to convert a dataframe to XML but we will show you how to do it with a simple custom function. This is very useful especialy when working with flask and you want your API to have as output an XML file.

#lets create a dataframe
   A  B
0  1  a
1  2  b
2  3  c
3  4  d
4  5  e

to_xml Function

def to_xml(df):
    def row_xml(row):
        xml = ['<item>']
        for i, col_name in enumerate(row.index):
            xml.append('  <{0}>{1}</{0}>'.format(col_name, row.iloc[i]))
        return '\n'.join(xml)
    res = '\n'.join(df.apply(row_xml, axis=1))
'<item>\n  <A>1</A>\n  <B>a</B>\n</item>\n<item>\n  <A>2</A>\n  <B>b</B>\n</item>\n<item>\n  <A>3</A>\n  <B>c</B>\n</item>\n<item>\n  <A>4</A>\n  <B>d</B>\n</item>\n<item>\n  <A>5</A>\n  <B>e</B>\n</item>'

Above you can see that you will get a string and that’s ok because when it’s rendered it will be in a nice XML format like below.


Save XML file

with open('df.XML', 'w') as f:

Bonus: How to return XML files in Flask

#you need to import Response
from flask import Response

def test():
    xml = to_xml(df)
    return Response(xml, mimetype='text/xml')

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore


Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.


Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s