尝试附加到熊猫数据框中时获取“真实”值而不是实际值

时间:2018-10-25 07:41:25

标签: python pandas append

下面是我的python脚本。我正在尝试解析xml文件,并尝试将值存储在pandas数据框中,以便以后可以将其更改为csv文件。

import os
import pandas as pd
import sys
import requests
import xml.etree.ElementTree as ET
from xml.dom import minidom

tree = ET.parse('schedule.xml')
FILENAME = sys.argv[1]
COL_NAMES = ['PODNAME', 'DC', 'Upgrade']
DF = pd.DataFrame(columns = COL_NAMES)
root = tree.getroot()

def parseXml(DF, filePath):

    xmldoc = minidom.parse(filePath)
    PODs= xmldoc.getElementsByTagName("POD")
    name=[]
    DC=[]
    deferUpgrade=[]
    for pod in PODs:
        if pod.hasAttribute("name") and pod.hasAttribute("DC") and pod.hasAttribute("deferUpgrade"):
            DF = DF.append({'PODNAME': pod.getAttribute("name"), 'DC': pod.hasAttribute("DC"), 'Upgrade': pod.hasAttribute("deferUpgrade")}, ignore_index=True)
    return(DF)


DF = parseXml(DF, FILENAME)

下面是XML文件

<Schedule xmlns="http://xmlns.xyz.com/fal/downtimeschedule/V1.0">
 <Downtime end="20181020000" id="10001197610_20181027000_201810000" mode="cold" start="20181020000"/>
 <PODS>
  <POD DC="US - Washing" deferUpgrade="true" name="ABCD" patching="Production" EndTime="20181028040000">
   <CR id="12345"/>
   <CR id="12346"/>
   <CR id="123"/>
  </POD>
  <POD DC="US - Washing" deferUpgrade="true" name="ABCD-TEST" patching="Production" EndTime="20181028040000">
   <CR id="12345"/>
   <CR id="12346"/>
   <CR id="123"/>
  </POD>
 </PODS>

当我使用第一个参数作为文件名运行脚本时,我的输出低于输出

     PODNAME    DC Upgrade
0       ABCD  True    True
1  ABCD-TEST  True    True

但是,我期望下面的输出。

     PODNAME    DC            Upgrade
0       ABCD  US - Washing    true
1  ABCD-TEST  US - Washing    true

此外,我尝试使用concat来解决上述问题,但低于输出量

       PODNAME              DC Upgrade
0       [ABCD]  [US - Washing]  [true]
1  [ABCD-TEST]  [US - Washing]  [true]

1 个答案:

答案 0 :(得分:0)

正如Nitin和Martin回答的那样,将最终代码粘贴到这里。

import os
import pandas as pd
import sys
import requests
import xml.etree.ElementTree as ET
from xml.dom import minidom

tree = ET.parse('schedule.xml')
FILENAME = sys.argv[1]
COL_NAMES = ['PODNAME', 'DC', 'Upgrade']
DF = pd.DataFrame(columns = COL_NAMES)
root = tree.getroot()

def parseXml(DF, filePath):

    xmldoc = minidom.parse(filePath)
    PODs= xmldoc.getElementsByTagName("POD")
    name=[]
    DC=[]
    deferUpgrade=[]
    for pod in PODs:
        if pod.hasAttribute("name") and pod.hasAttribute("DC") and pod.hasAttribute("deferUpgrade"):
            DF = DF.append({'PODNAME': pod.getAttribute("name"), 'DC': pod.getAttribute("DC"), 'Upgrade': pod.getAttribute("deferUpgrade")}, ignore_index=True)
    return(DF)


DF = parseXml(DF, FILENAME)