I want to save numpy.array data into XML file, then read it again. following is my code:
array to string
arr=numpy.zeros((20))
s = str(arr)
But This way would generate enter key and '[',']' characters in the string.
string to array
I should remove the enter key and '[',']' first. And then use numpy.fromstring
But I don't think that's a good way to do that. And that can't work on 2-D array
3 Answers 3
You are mixing two different ways of doing "to string":
a = numpy.zeros((20))
you can, after stripping newlines and [] from it, put str(a) in a new numpy.matrix() constructor and initialize numpy.array() with the returned value:
b = numpy.array(numpy.matrix(" ".join(str(a).split()).strip('[]')))
or you can combine numpy.array.tostring() with numpy.fromstring():
c = numpy.fromstring(a.tostring())
but mixing and matching like you tried to do does not work.
3 Comments
Enter key. So numpy.array also can't worknumpy.array(str(a)) is not the same as a. the result seems to be a "0D-array" holding just the string as sole element. The other method seems to work though.str(a), see my edit.You can easily turn numpy arrays into regular python lists and vice versa. You could then store the string representation of the list to file, load it from file, turn it back into a list and into a numpy array.
>>> list(numpy.zeros(4))
[0.0, 0.0, 0.0, 0.0]
>>> numpy.array([0.0, 0.0, 0.0, 0.0])
array([ 0., 0., 0., 0.])
Using the map function, this also works for 2D-arrays.
>>> map(list, numpy.zeros((2, 3)))
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
>>> numpy.array([[0.0, 0.0], [0.0, 0.0]])
array([[ 0., 0., 0.],
[ 0., 0., 0.]])
However, if the array is really big it might still be better to store it using numpy.save and numpy.load and use the XML file only to store the path to that file, together with a comment.
4 Comments
.npy file, as suggested in a comment, and put the name of the file, together with a comment, into XML.map(list,numpy.zeros(2)). It generate TypeError: 'numpy.float64' object is not iterableerror. why?list(your_array). map is only for 2D arrays.In addition to dumping the ndarray to a .npy file using save and load and noting the details of that file in your xml, you could create a string with the data as noted by Nils Werner.
Note: you might want to check out HDF or pytables (which uses hdf).
List