我目前正在使用lxml获取XML文件,然后从根元素创建一个pandas数据框。我实际上是在用这个例子。我这样做是为了做一些数学运算/对数据进行建模。
我想要实现的下一步是能够将数据写回xml文档。在我脚本的其他地方,我使用了root.insert
,因为我可以强制在特定位置插入索引,以保持xml文档的整洁和连贯。
是否有一种方法,我可以写出数据框的每一行使用像root.insert(position, data)
在数据框的每一行,其中的数据框列标头是标签?
示例XML
<Root_Data>
<SomeData></SomeData>
<SomeOtherData></SomeOtherData>
<Weather>
<WxId>1</WxId>
<Temp>20></WxId>
<WindSpeed>15</WindSpeed>
</Weather>
# We will insert more weather here - I can find this position index. Assume it is 3.
<SomeMoreData></SomeMoreData>
<Root_Data>
熊猫dataframe:
ID Temp Windspeed
2 25 30
3 30 15
4 15 25
我提供了一些代码,我已经尝试到目前为止-但我实际上已经空手而归,如何插入行从一个数据框到xml文档,而不手动构建xml作为字符串自己(不是很好-标题可能会改变,这就是为什么我想使用列标题作为标签)。
预期的结果
<Root_Data>
<SomeData></SomeData>
<SomeOtherData></SomeOtherData>
<Weather>
<WxId>1</WxId>
<Temp>20></WxId>
<WindSpeed>15</WindSpeed>
</Weather>
<Weather>
<WxId>2</WxId>
<Temp>25></WxId>
<WindSpeed>30</WindSpeed>
</Weather>
<Weather>
<WxId>3</WxId>
<Temp>30></WxId>
<WindSpeed>15</WindSpeed>
</Weather>
<Weather>
<WxId>4</WxId>
<Temp>15></WxId>
<WindSpeed>25</WindSpeed>
</Weather>
<SomeMoreData></SomeMoreData>
<Root_Data>
目前的示例代码:
from lxml import etree
import pandas as pd
tree = etree.parse('example.xml')
root = tree.getroot()
#Load into dataframe
for node in root:
res=[]
df_cols = ["WxId","Temp", "WindSpeed"]
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)
out_df = out_df[~out_df['Temp'].isnull()] #Proxy for good / bad data. Remove nulls.
#Now, write from data frame back to root so we can structure the XML before writing to file.
# ? Unknown method
另一种方法,如果您的列未定义或将来可能会增加。
df = pd.read_csv('./123.csv')
root = etree.Element("root")
for rows in range(0,df.shape[0]):
Tag = etree.Element('weather')
for cols in range(0,df.shape[1]):
etree.SubElement(Tag,df.iloc[rows:,cols].head().name).text = str(df.iloc[rows][cols])
# Append Element "Tag" to the Main Root here
root.append(Tag)
print(etree.tostring(root,encoding='Unicode'))
您可以使用to_xml
将您的数据帧转换为xml:
xdata = df.rename(columns={'ID': 'WxId'})
.to_xml(index=False, root_name='Root_Data', row_name='Weather')
>>> xdata
<?xml version='1.0' encoding='utf-8'?>
<Root_Data>
<Weather>
<WxId>2</WxId>
<Temp>25</Temp>
<Windspeed>30</Windspeed>
</Weather>
<Weather>
<WxId>3</WxId>
<Temp>30</Temp>
<Windspeed>15</Windspeed>
</Weather>
<Weather>
<WxId>4</WxId>
<Temp>15</Temp>
<Windspeed>25</Windspeed>
</Weather>
</Root_Data>
现在您可以使用lxml
插入数据之前的第一个子Weather
和最后一个子Weather
或插入您的xdata在您的原始xml文件的某个地方。
供参考,您可以使用pd.read_xml
将您的xml转换为数据框架