Python Pandas数据框到XML

Python Pandas数据框到XML,第1张

Python Pandas数据框到XML

首先摆脱方法中的

Series
标签
to_xml

def to_xml(df, filename=None, mode='w'):    def row_to_xml(row):        date = row.TIMESTAMP.split()[0]        time = row.TIMESTAMP.split()[1]        value = row.A        xml = '<event date="{0}" time="{1}" value="{2}"></event>'.format(date, time, value)        return xml    res = ' '.join(df.apply(row_to_xml, axis=1))    if filename is None:        return res    with open(filename, mode) as f:        f.write(res)

然后,您可以像这样创建XML树:

*from xml.dom.minidom import parseStringdoc = document()base = doc.createElement('Timeseries')doc.appendChild(base)series = parseString('<Series>' + to_xml(df) + '</Series>').childNodes[0]base.appendChild(series)base.appendChild(series)header = doc.createElement('Header')series.appendChild(header)type = doc.createElement('type')type_content = doc.createTextNode('instantaneous')type.appendChild(type_content)header.appendChild(type)timeStepElem = doc.createElement('timeStep')timeStepElem.setAttribute ('unit','minute')timeStepElem.setAttribute ('multiplier','5')header.appendChild(timeStepElem)startDateElem = doc.createElement('startDate')startDateElem.setAttribute ('time','13:30:00')startDateElem.setAttribute ('date','2015-06-24')header.appendChild(startDateElem)print(doc.toprettyxml())*

输出

<?xml version="1.0" ?><Timeseries>        <Series>     <event date="2015/03/09" time="15:40" value="52.2885"/>     <event date="2015/03/09" time="15:50" value="52.3277"/>     <event date="2015/03/09" time="16:00" value="52.5045"/>     <event date="2015/03/09" time="16:10" value="52.5702"/>     <event date="2015/03/09" time="16:20" value="52.5608"/>     <Header>  <type>instantaneous</type>  <timeStep multiplier="5" unit="minute"/>  <startDate date="2015-06-24" time="13:30:00"/>     </Header>        </Series></Timeseries>


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5648779.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存