Reputation: 6247
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
Upvotes: 0
Views: 555
Reputation: 36849
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.
Upvotes: 2
Reputation: 82949
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.
Upvotes: 1
Reputation: 351
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).
Upvotes: 0