简体   繁体   English

将numpy数组转换为给定格式的字符串

[英]convert numpy array to string with given format

I would like to convert a numpy array into a string representation with a given format.我想将 numpy 数组转换为具有给定格式的字符串表示形式。 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.有效,但savetxt很慢。 tofile is about twice as fast, but I don't know how to get it to work with BytesIO . tofile大约快两倍,但我不知道如何让它与BytesIO一起工作。 Perhaps there is another alternative.也许还有另一种选择。

Any hints?任何提示?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM