您的位置:首页 > 编程语言 > Python开发

Python读取XML中数据提取为Dataframe

2018-08-03 11:59 543 查看

对应的数据集为:

[code]<?xml version="1.0"?>
-<opencv_storage>
-<vocabulary type_id="opencv-matrix">
<rows>424</rows>
<cols>512</cols>
<dt>u</dt>
<data> 0 0 0 0 0 0 0 0 0 145 169 255 255 0 0 0 0 0 0 0 0 0 0 0 0 0 255 0 0 0 205 0 0 0 0
0 0 0 0 0 0 0 0 227 0 0 158 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 150 0 0 0 0 0 0 152 0 0 0 144 0 139 0 148 0 0 0 0 0 153 0 0 148 0 0 0 0 0 154 0 0 0
0 58 156 0 0 0 0 0 150 0 0 0 0 0 154 153 0 0 219 0 0 0 144 153 158 149 153 0 0 0 150
148
0 0 0 154 143 0 145 0 152 0 154 148 153 162 148 155 146 0 144 0 152 145 154 0 0 0 0 151
153 148 153 156 0 144 0 0 0 0 0 0 0 0 0 143 0 153 142 0 0 0 0 0 0 0 0 0 154 148 0 148
158 148 147 152 154 158 155 150 150 0 151 0 148 151 157 152 149 148 150 145 153 151 153
153 0 152 147 158 151 152 155 154 149 147 151 150 0 151 154 142 148 149 0 152 151 0 146
147 147 151 148 146 154 153 149 0 151 153 149 150 151 156 148 152 150 146 150 148 151
153 154 157 153 150 155 152 150 149 152 150 147 </data>
</vocabulary>
</opencv_storage>

对应的处理代码:

[code]import numpy as np
import pandas as pd
import xml.dom.minidom
#打开xml文档
dom = xml.dom.minidom.parse('D:/xuchao.xml')

#得到文档元素对象,拿出<data>间的数据
root = dom.documentElement
cp=dom.getElementsByTagName('data')
c1=cp[0]
c2=c1.firstChild.data

#先根据换行符拆分
result=c2.split('\n')
#得到的list第一行为空,去除这行
result.remove(result[0])

#根据空格把数字拆分出来,得到每行list,切片将空值切去
b=[]
for lines in result:
c=lines.split(' ')
c=c[4:]
for j in c:
b.append(j)

#转化为mat
b=np.array(b)
#源数据得到424*512,上面数据集没有这么多元素
mat=b.reshape(424,512)
df=pd.Dataframe(mat)

部分Python用法参考:

1.Python四种逐行读取文件内容的方法

2.list 删除一个元素的三种做法

3.Python 之处理字符串中的空格

4.Python中的split()函数的用法

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐