Reputation: 58721
I would like to convert a numpy array into a string representation with a given format. This
from io import BytesIO
import numpy
data = numpy.random.rand(5)
s = BytesIO()
numpy.savetxt(s, data, "%.15e")
out = s.getvalue().decode()
print(out)
3.208726298090422e-01
6.817590490300521e-01
3.446035342640975e-01
7.871066165361260e-01
4.829308426574872e-01
works, but savetxt
is slow. tofile
is about twice as fast, but I don't know how to get it to work with BytesIO
. Perhaps there is another alternative.
Any hints?
Upvotes: 3
Views: 1019
Reputation: 1252
You can do something like this:
import numpy as np
data = np.random.rand(5)
out ='\n'.join(map('{:.15e}'.format, data))
print(out)
Output example:
2.599889521964338e-02
8.936410392960248e-01
7.074905121425787e-01
4.318334519811902e-01
8.219700656108224e-01
Upvotes: 2