[英]Python/Pandas: updating a XML-file from pandas DataFrame
我正在嘗試使用 Pandas DataFrame 中的數據更新 xml 文件:xml 文件如下所示:
<root>
<NetworkData>
<Element loadid="23" type="Load" node1="N23">
<Name>load1</Name>
<ShortName/>
<InputState>1027</InputState>
<x>11</x>
<y>15</y>
</Element>
<Element loadid="24" type="Load" node1="N24">
<Name>load2</Name>
<ShortName/>
<InputState>1027</InputState>
<x>0.75</x>
<y>600</y>
</Element>
...
數據框看起來像:
ID | X | 是 |
---|---|---|
23 | 17 | 29 |
24 | 123 | 543 |
... | ... | ... |
該ID
與 xml 文件中的loadid
相同。 我的目標是使用 Dataframe 中的值更新 xml 文件中的值x
和y
。 有沒有一種簡單的方法可以做到這一點,因為 Dataframe 很長? 順便說一下,所有loadids
都可以在 Dataframe 中作為IDs
找到。 輸出 xml 文件:
<root>
<NetworkData>
<Element loadid="23" type="Load" node1="N23">
<Name>load1</Name>
<ShortName/>
<InputState>1027</InputState>
<x>17</x>
<y>29</y>
</Element>
<Element loadid="24" type="Load" node1="N24">
<Name>load2</Name>
<ShortName/>
<InputState>1027</InputState>
<x>123</x>
<y>543</y>
</Element>
...
謝謝!
import pandas as pd
from lxml import etree
# create test dataframe
df = pd.DataFrame({
'ID': [23,24,25,26,27],
'x': [21,22,23,24,25],
'y': [101,102,103,104,105]
})
# create xml as a string (in your code it could be a file)
text = '''<root>
<NetworkData>
<Element loadid="23" type="Load" node1="N23">
<Name>load1</Name>
<ShortName/>
<InputState>1027</InputState>
<x>11</x>
<y>15</y>
</Element>
<Element loadid="24" type="Load" node1="N24">
<Name>load2</Name>
<ShortName/>
<InputState>1027</InputState>
<x>0.75</x>
<y>600</y>
</Element>
<Element loadid="99" type="Load" node1="N24">
<Name>load2</Name>
<ShortName/>
<InputState>1027</InputState>
<x>0.75</x>
<y>600</y>
</Element>
</NetworkData>
</root>
'''
# convert string to xml
# (in your code it could be read from file instead)
doc = etree.fromstring(text)
# iterate over elements "Element"
for el in doc.xpath(".//NetworkData/Element"):
# retrieve id from attribute value
id = el.get('loadid')
# retrieve appropriate row from dataframe
row = df[df['ID'] == int(id)]
# if found, update x and y
if len(row) == 1:
# find "x" element
x = el.find('./x')
# if found, update
if x is not None:
x.text = str(row['x'].item())
# find "y" element
y = el.find('./y')
# if found update
if y is not None:
y.text = str(row['y'].item())
# if there was no match found, update x and y with "0" values
elif len(row) == 0:
# find "x" element
x = el.find('./x')
# if found, update
if x is not None:
x.text = '0'
# find "y" element
y = el.find('./y')
# if found update
if y is not None:
y.text = '0'
# save changed XML
# ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.