python/pandas:从pandas Dataframe 更新xml文件

xxslljrj  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(370)

我正在尝试使用数据框中的数据更新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>
        ...

Dataframe 看起来像:
idxy23172924123543。。。。。。。。。
这个 IDloadid 在xml文件中。我的目标是更新这些值 xy 在xml文件中包含来自 Dataframe 的值。有没有一种简单的方法可以做到这一点,因为 Dataframe 相当长?顺便说一下 loadids 如图所示 IDs 在 Dataframe 中。输出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>
        ...

非常感谢。

kqlmhetl

kqlmhetl1#

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>
    </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())

# save changed XML

# ...

相关问题