Improve speed parsing XML with elements and namespace, into Pandas

别说谁变了你拦得住时间么 提交于 2021-02-08 07:37:23

问题


So I have a 52M xml file, which consists of 115139 elements.

from lxml import etree
tree  = etree.parse(file)
root  = tree.getroot()
In [76]: len(root)
Out[76]: 115139

I have this function that iterates over the elements within root and inserts each parsed element inside a Pandas DataFrame.

def fnc_parse_xml(file, columns):
    start = datetime.datetime.now()
    df    = pd.DataFrame(columns=columns)
    tree  = etree.parse(file)
    root  = tree.getroot()
    xmlns = './/{' + root.nsmap[None] + '}'

    for loc,e in enumerate(root):
        tot = []
        for column in columns:
            tot.append(e.find(xmlns + column).text)
        df.at[loc,columns] = tot

    end = datetime.datetime.now()
    diff = end-start
    return df,diff

This process works but it takes a lot of time. I have an i7 with 16GB of RAM.

In [75]: diff.total_seconds()/60                                                                                                      
Out[75]: 36.41769186666667
In [77]: len(df)                                                                                                                      
Out[77]: 115139

I'm pretty sure there is a better way of parsing a 52M xml file into a Pandas DataFrame.

This is an extract of the xml file ...

<findToFileResponse xmlns="xmlapi_1.0">
    <equipment.MediaIndependentStats>
        <rxOctets>0</rxOctets>
        <txOctets>0</txOctets>
        <inSpeed>10000000</inSpeed>
        <outSpeed>10000000</outSpeed>
        <time>1587080746395</time>
        <seconds>931265</seconds>
        <port>Port 3/1/6</port>
        <ip>192.168.157.204</ip>
        <name>RouterA</name>
    </equipment.MediaIndependentStats>
    <equipment.MediaIndependentStats>
        <rxOctets>0</rxOctets>
        <txOctets>0</txOctets>
        <inSpeed>100000</inSpeed>
        <outSpeed>100000</outSpeed>
        <time>1587080739924</time>
        <seconds>928831</seconds>
        <port>Port 1/1/1</port>
        <ip>192.168.154.63</ip>
        <name>RouterB</name>
    </equipment.MediaIndependentStats>
</findToFileResponse>

any ideas on how to improve speed?

For the extract of the above xml, the function fnc_parse_xml(file, columns) returns this DF....

In [83]: df                                                                                                                           
Out[83]: 
  rxOctets txOctets   inSpeed  outSpeed           time seconds        port               ip     name
0        0        0  10000000  10000000  1587080746395  931265  Port 3/1/6  192.168.157.204  RouterA
1        0        0    100000    100000  1587080739924  928831  Port 1/1/1   192.168.154.63  RouterB

回答1:


Another option instead of building a tree by parsing the entire XML file is to use iterparse...

import datetime
import pandas as pd
from lxml import etree


def fnc_parse_xml(file, columns):
    start = datetime.datetime.now()
    # Capture all rows in array.
    rows = []
    # Process all "equipment.MediaIndependentStats" elements.
    for event, elem in etree.iterparse(file, tag="{xmlapi_1.0}equipment.MediaIndependentStats"):
        # Each row is a new dict.
        row = {}
        # Process all chidren of "equipment.MediaIndependentStats".
        for child in elem.iterchildren():
            # Create an entry in the row dict using the local name (without namespace) of the element for
            # the key and the text content as the value.
            row[etree.QName(child.tag).localname] = child.text
        # Append the row dict to the rows array.
        rows.append(row)
    # Create the DateFrame. This would probably be better in a try/catch to handle errors.
    df = pd.DataFrame(rows, columns=columns)
    # Calculate time difference.
    end = datetime.datetime.now()
    diff = end - start
    return df, diff


print(fnc_parse_xml("input.xml",
                    ["rxOctets", "txOctets", "inSpeed", "outSpeed", "time", "seconds", "port", "ip", "name"]))

On my machine this processes a 92.5MB file in about 4 seconds.




回答2:


You declare an empty dataframe, so you might get a speedup if you specify the index ahead of time. Otherwise, there is constant expansion of the dataframe.

df = pd.DataFrame(index=range(0, len(root)))

You could also create the dataframe at the end of the loop.

vals = [[e.find(xmlns + column).text for column in columns] for e in root]
df = pd.DataFrame(data=vals, columns=['rxOctets', ...])



回答3:


we'll make use of a library xmltodict - allows you to treat xml documents like a dict/json. the data you are interested in is embedded in the equipment.MediaIndependentStats 'key' :

import xmltodict
data = """<findToFileResponse xmlns="xmlapi_1.0">
    <equipment.MediaIndependentStats>
        <rxOctets>0</rxOctets>
        <txOctets>0</txOctets>
        <inSpeed>10000000</inSpeed>
        <outSpeed>10000000</outSpeed>
        <time>1587080746395</time>
        <seconds>931265</seconds>
        <port>Port 3/1/6</port>
        <ip>192.168.157.204</ip>
        <name>RouterA</name>
    </equipment.MediaIndependentStats>
    <equipment.MediaIndependentStats>
        <rxOctets>0</rxOctets>
        <txOctets>0</txOctets>
        <inSpeed>100000</inSpeed>
        <outSpeed>100000</outSpeed>
        <time>1587080739924</time>
        <seconds>928831</seconds>
        <port>Port 1/1/1</port>
        <ip>192.168.154.63</ip>
        <name>RouterB</name>
    </equipment.MediaIndependentStats>
</findToFileResponse>"""


pd.concat(pd.DataFrame.from_dict(ent,orient='index').T
          for ent in xmltodict.parse(data)['findToFileResponse']['equipment.MediaIndependentStats'])

rxOctets    txOctets    inSpeed outSpeed    time    seconds port    ip  name
0   0   0   10000000    10000000    1587080746395   931265  Port 3/1/6  192.168.157.204 RouterA
0   0   0   100000  100000  1587080739924   928831  Port 1/1/1  192.168.154.63  RouterB


来源:https://stackoverflow.com/questions/61334751/improve-speed-parsing-xml-with-elements-and-namespace-into-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!