我有太大的数据和太小的 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/