3

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?

3
  • savetxt creates a fmt string by replicating that %... to match the number of columns in data. It then does fmt % tuple(row). The Python string formatting mechanism works on individual numbers (and by extension tuples of numbers), not on arrays. Commented Aug 7, 2019 at 17:52
  • Just curious, instead of using BytesIO, wouldn't .npy files, i.e. np.save in byte encoded format do your job? Commented Aug 7, 2019 at 19:13
  • @SayandipDutta I don't want the file, I want the string. Commented Aug 7, 2019 at 19:47

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.