问题描述
我正在尝试从 XML 文件创建数据框,但我似乎无法做到,因为 XML 文件中有多个嵌套部分。缩进由 rMonthly,rSP500,rVenues and rVenue
表示。我试图粘贴下面的 XML 文件,但不幸的是,它完全不可读,而且缩进没有正确显示。但是,XML 文件包含在以下网站的 zip 文件中
http://public.s3.com/rule606/hood/
我正在尝试创建一个看起来像这样的表,其中包含“年”、“月”和“名称”列:
Spreadsheet with columns for "year","month" and "name"
我尝试创建一个数据框以从 XML 中获取数据,但似乎无法读取嵌套在 XML 深处的元素。我的代码如下,但它为所有变量返回[none]
import pandas as pd
import xml.etree.ElementTree as et
xtree = et.parse(xml_file)
xroot = xtree.getroot()
rows = []
df_cols = ["year","mon","name"]
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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)