I am having a hard time generating a .xml
file from a Pandas DataFrame. I am using this solution (How do convert a pandas/dataframe to XML?) (sorry, for some reason stack wont let me link a word to the site), but am trying to add an additional field. The original solution works if I do not include the shape
parameters, but I do need to add the values into the .xml
file. I am not sure why I cannot call the function with the arguments. In addition to calling the function, I am having a hard time writing as an xml. I have searched through a few other stack questions and have found that this code chunk works, but when I open the .xml
file I get only four numbers (30, 1, 67, 44) which are the. Though if I open it in pycharm I get the "desired" view.
file_handle = open("output.xml", "w")
Q.writexml(file_handle)
file_handle.close()
Code:
print(image_x.shape)
output: (185, 186, 3)
width = image_x.shape[0]
height = image_x.shape[1]
depth = image_x.shape[2]
def func(row, width, height, depth):
xml = ['<item>']
shape = [f'<width>{width}</width>\n<height>{height}</height>\n<depth>{depth}</depth>']
for field in row.index:
xml.append(' <{0}>{1}</{0}>'.format(field, row[field]))
xml.append('</item>')
xml.append(shape)
return '\n'.join(xml)
xml_file = func(df, width, height, depth)
df:
xmin ymin xmax ymax
0 30 1 67 44
1 39 136 73 176
Error:
Traceback (most recent call last):
File "D:\PyCharmEnvironments\lib\site-packages\pandas\core\indexes\base.py", line 3080, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 70, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 101, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 4554, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 4562, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 0
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:/PycharmProjects/Augmentation/random_shit.py", line 100, in <module>
Q = func(df, width, height, depth)
File "D:/PycharmProjects/Augmentation/random_shit.py", line 95, in func
xml.append(' <{0}>{1}</{0}>'.format(field, row[field]))
File "D:\PyCharmEnvironments\lib\site-packages\pandas\core\frame.py", line 3024, in __getitem__
indexer = self.columns.get_loc(key)
File "D:\PyCharmEnvironments\lib\site-packages\pandas\core\indexes\base.py", line 3082, in get_loc
raise KeyError(key) from err
KeyError: 0
Desired Output:
<annotations>
<size>
<width>185</width>
<height>186</height>
<depth>3</depth>
</size>
<item>
<xmin>30</xmin>
<ymin>1</ymin>
<xmax>67</xmax>
<ymax>44</ymax>
</item>
<item>
<xmin>39</xmin>
<ymin>136</ymin>
<xmax>73</xmax>
<ymax>176</ymax>
</item>
</annotations>