How to export numpy ndarray to a string variable?
Asked Answered
D

2

6

I am trying to write an xml file using the code below:

def make_xml(a_numpy_array):

    from lxml import etree as ET

    root = ET.Element('intersections')
    intersection = ET.SubElement(root, 'intersection')
    trace = ET.SubElement(intersection, 'trace')
    trace.text = a_numpy_array

    print ET.tostring(root, pretty_print=True, xml_declaration=True, encoding = 'utf-8')

.....

trace.text expects a string input. I want to put in the xml file here a 2D array stored as a numpy ndarray. But I cannot seem to be able to export the data to a string. numpy.tostring gives me bytecode, what do I do with that? the solution ive come up with is to write the ndarray to a text file and then read the text file as a string but I would like to be able to skip writing a text file.

Dimpledimwit answered 15/7, 2014 at 17:6 Comment(0)
S
2

You can do

trace.text = str(a_numpy_array)

For more options, see numpy.array_str and numpy.array2string.

Slicer answered 15/7, 2014 at 19:23 Comment(0)
C
2

You could use np.savetxt to write the array to a io.BytesIO() (instead of a file).

import numpy as np
from lxml import etree as ET
import io

root = ET.Element('intersections')
intersection = ET.SubElement(root, 'intersection')
trace = ET.SubElement(intersection, 'trace')

x = np.arange(6).reshape((2,3))
s = io.BytesIO()
np.savetxt(s, x)
trace.text = s.getvalue()

print(ET.tostring(root, pretty_print=True, xml_declaration=True, encoding = 'utf-8'))

yields

<?xml version='1.0' encoding='utf-8'?>
<intersections>
  <intersection>
    <trace>0.000000000000000000e+00 1.000000000000000000e+00 2.000000000000000000e+00
3.000000000000000000e+00 4.000000000000000000e+00 5.000000000000000000e+00
</trace>
  </intersection>
</intersections>

Then you could load the data back into a NumPy array using np.loadtxt:

for trace in root.xpath('//trace'):
    print(np.loadtxt(io.BytesIO(trace.text)))

yields

[[ 0.  1.  2.]
 [ 3.  4.  5.]]
Checkmate answered 15/7, 2014 at 17:14 Comment(0)
S
2

You can do

trace.text = str(a_numpy_array)

For more options, see numpy.array_str and numpy.array2string.

Slicer answered 15/7, 2014 at 19:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.