如何在str(numpy.float64)上设置精度? [英] How to set the precision on str(numpy.float64)?

查看:581
本文介绍了如何在str(numpy.float64)上设置精度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将几个numpy浮点数写入具有附加字符串内容的csv文件.因此,我不将savetxt等与numpy.set_printoptions()一起使用,我只能定义打印行为,而不能定义str()行为.我知道我想念一些东西,而且不会那么难,但是我在互联网上找不到合理的答案.也许有人可以指出我正确的方向.这里是一些示例代码:

i need to write a couple of numpy floats to a csv-file which has additional string content. therefore i dont use savetxt etc. with numpy.set_printoptions() i can only define the print behaviour, but not the str() behaviour. i know that i miss something and it cant be that hard, but i dont find a reasonable answer on the interwebs. maybe someone can point me in the right direction. heres some example code:

In [1]: import numpy as np
In [2]: foo = np.array([1.22334])

In [3]: foo
Out[3]: array([ 1.22334])

In [4]: foo[0]
Out[4]: 1.2233400000000001

In [5]: str(foo[0])
Out[5]: '1.22334'

In [6]: np.set_printoptions(precision=3)

In [7]: foo
Out[7]: array([ 1.223])

In [8]: foo[0]
Out[8]: 1.2233400000000001

In [9]: str(foo[0])
Out[9]: '1.22334'

如何将np.float转换为格式正确的字符串,可以将其提供给file.write()?

How do i convert np.float to a nicely formatted string, which i can feed to file.write()?

亲切的问候,

fookatchu

fookatchu

推荐答案

您可以只使用标准的字符串格式:

You can just use standard string formatting:

>>> x = 1.2345678
>>> '%.2f' % x
'1.23'

这篇关于如何在str(numpy.float64)上设置精度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆