python-2.7 - 对整个笔记本应用舍入设置

标签 python-2.7 numpy

我有太大的数据和太小的 numpy 数组形式的数据。和太多的计算。我不想到处应用 round(num,k)。有什么办法可以进行一些全局设置以将所有内容四舍五入到小数点后三位吗?我使用 Ipython 笔记本。

最佳答案

使用 np.set_printoptions :

In [1]: import numpy as np

In [2]: np.random.randn(5)
Out[2]: array([-0.15421429, -1.3773473 ,  0.89456261, -0.17368004, -0.92570868])

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

In [4]: np.random.randn(5)
Out[4]: array([-0.497, -1.057, -0.638, -0.566,  0.077])

在 IPython session 中,您还可以使用 %precision 魔法来做同样的事情:

In [5]: %precision 2
Out[5]: u'%.2f'

In [6]: np.random.randn(5)
Out[6]: array([-1.06,  0.33, -1.8 ,  0.74, -0.73])

请注意,这只影响数字的显示方式 - 在幕后,numpy 仍然使用完整的浮点精度(np.double ~15 位小数)在其计算中。


看来 OP 有兴趣将数组写入具有较少小数位精度的文本文件,而不是它们的显示方式。

将 numpy 数组写入文本文件的一种方法是使用 np.savetxt 。此函数采用 fmt 参数,它允许您指定任意字符串格式,包括要打印的小数位数。

例如:

x = np.random.randn(10)

# this writes the array out to 6 decimal places
np.savetxt('six_dp.txt', x, fmt='.6f')

# this writes the same array to 3 decimal places
np.savetxt('three_dp.txt', x, fmt='.3f')

您可以阅读更多关于字符串格式化在 Python here 中的工作原理。

关于python-2.7 - 对整个笔记本应用舍入设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25200609/

相关文章:

python - 大型二维 numpy 数组中相同元素的高效成对计算

python-2.7 - 使用 .boto 谷歌云存储 API 进行身份验证

python - 在Python中跳过某些文件夹

python - 如何在 python 中保存来自 selenium 和 opencv 的部分屏幕截图

python - 为什么 pd.to_numeric 不适用于大数字?

Python Numpy Matplotlib 设置 Y 标签内联

python - 新型 python 缓冲协议(protocol)和 numpy 数组

python - 日志记录 - 合并多个配置文件

python - 如何在python中循环多个文件并逐一处理

python - 如何过滤掉嵌套列表中的条件逻辑元素