How to convert an XML file to nice pandas dataframe?

前端 未结 4 1785
一向
一向 2020-11-22 16:30

Let\'s assume that I have an XML like this:



        
4条回答
  •  感动是毒
    2020-11-22 17:06

    You can also convert by creating a dictionary of elements and then directly converting to a data frame:

    import xml.etree.ElementTree as ET
    import pandas as pd
    
    # Contents of test.xml
    #               
    
    root = ET.parse('test.xml').getroot()
    
    tags = {"tags":[]}
    for elem in root:
        tag = {}
        tag["Id"] = elem.attrib['Id']
        tag["TagName"] = elem.attrib['TagName']
        tag["Count"] = elem.attrib['Count']
        tags["tags"]. append(tag)
    
    df_users = pd.DataFrame(tags["tags"])
    df_users.head()
    

提交回复
热议问题