提高将 XML 与元素和命名空间解析为 Pandas 的速度

Improve speed parsing XML with elements and namespace, into Pandas

所以我有一个 52M xml 文件,它由 115139 个元素组成。

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

我有这个函数迭代 root 中的元素并将每个解析的元素插入到 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

这个过程有效,但需要很多时间。我有一个 16GB RAM 的 i7。

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

我很确定有更好的方法将 52M xml 文件解析为 Pandas DataFrame。

这是 xml 文件的摘录...

<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>

关于如何提高速度有什么想法吗?

对于上面xml的摘录,函数fnc_parse_xml(file, columns)returns这个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

您声明了一个空数据帧,因此如果您提前指定索引,您可能会获得加速。否则,数据框会不断扩展。

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

您也可以在循环结束时创建数据框。

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

我们将使用库 xmltodict - 允许您像 dict/json 一样处理 xml 文档。您感兴趣的数据嵌入在 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

通过解析整个 XML 文件来构建树的另一种选择是使用 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"]))

在我的机器上,这会在大约 4 秒内处理一个 92.5MB 的文件。