【发布时间】:2021-04-04 01:33:03
【问题描述】:
我正在尝试使用以下方法将其转换为 Python 中的 DF:
import pandas as pd
import xml.etree.ElementTree as et
def parse_XML(xml_file, df_cols):
"""Parse the input XML file and store the result in a pandas
DataFrame with the given columns.
The first element of df_cols is supposed to be the identifier
variable, which is an attribute of each node element in the
XML data; other features will be parsed from the text content
of each sub-element.
"""
xtree = et.parse(xml_file)
xroot = xtree.getroot()
rows = []
for node in xroot:
res = []
res.append(node.attrib.get(df_cols[0]))
for el in df_cols[1:]:
if node is not None and node.find(el) is not None:
res.append(node.find(el).text)
else:
res.append(None)
rows.append({df_cols[i]: res[i]
for i, _ in enumerate(df_cols)})
out_df = pd.DataFrame(rows, columns=df_cols)
return out_df
我正在使用这样的功能:
parse_XML(R'C:\Users\aleks\Desktop\zadania python+sql\import_xml.xml', ['Year', 'Row', 'New', 'Used', 'Total Sales New', 'Total Sales Used'])
如何使它工作,以便将完整的 XML 文件导入 DataFrame?谢谢。
【问题讨论】:
-
请在帖子正文中发布示例 XML,而不是作为 minimal reproducible example 的图像。您可能需要考虑命名空间。另外,请修正您定义的方法的缩进。
标签: python xml pandas dataframe xml-parsing