【问题标题】:How to force a ndarray show in normal way instead of scientific notation?如何以正常方式而不是科学记数法强制显示 ndarray?
【发布时间】:2011-05-11 10:53:49
【问题描述】:

我正在尝试在屏幕上打印一个 ndarray。但是python总是用科学计数法显示,我不喜欢。对于标量,我们可以使用

>>> print '%2.4f' %(7.47212470e-01)
0.7472

但是如何为这样的 numpy.ndarray 做到这一点:

[[  7.47212470e-01   3.71730070e-01   1.16736538e-01   1.22172891e-02]
 [  2.79279640e+00   1.31147152e+00   7.43946656e-02   3.08162255e-02]
 [  6.93657970e+00   3.14008688e+00   1.02851599e-01   3.96611266e-02]
 [  8.49295040e+00   3.94730094e+00   8.99398479e-02   7.60969188e-02]
 [  2.01849250e+01   8.62584092e+00   8.75722302e-02   6.17109672e-02]
 [  2.22570710e+01   1.00291292e+01   1.20918359e-01   1.07250131e-01]
 [  2.82496660e+01   1.27882133e+01   1.08438172e-01   1.58723714e-01]
 [  5.89170270e+01   2.55268510e+01   1.31990966e-01   1.61599514e-01]]

.astype(float) 方法不改变结果,.round(4) 返回:

[[  7.47200000e-01   3.71700000e-01   1.16700000e-01   1.22000000e-02]
 [  2.79280000e+00   1.31150000e+00   7.44000000e-02   3.08000000e-02]
 [  6.93660000e+00   3.14010000e+00   1.02900000e-01   3.97000000e-02]
 [  8.49300000e+00   3.94730000e+00   8.99000000e-02   7.61000000e-02]
 [  2.01849000e+01   8.62580000e+00   8.76000000e-02   6.17000000e-02]
 [  2.22571000e+01   1.00291000e+01   1.20900000e-01   1.07300000e-01]
 [  2.82497000e+01   1.27882000e+01   1.08400000e-01   1.58700000e-01]
 [  5.89170000e+01   2.55269000e+01   1.32000000e-01   1.61600000e-01]]

我只是想要 0.7472 0.3717 等。

【问题讨论】:

    标签: python arrays matrix numpy scientific-notation


    【解决方案1】:

    numpy.set_string_function 函数可用于更改数组的字符串表示。

    您还可以使用numpy.set_print_options 更改默认使用的精度并关闭以科学计数法报告小数。

    来自set_print_options的示例:

    >>> np.set_printoptions(precision=4)
    >>> print np.array([1.123456789])
    [ 1.1235]
    

    【讨论】:

    • 这正是我想要的!谢谢!
    【解决方案2】:

    我不知道 numpy 数组,但我只是在用 Python 做项目时遇到了同样的问题。

    查看提供的 Decimal 类 http://docs.python.org/library/decimal.html

    我不知道它是否在 numpy 中提供。

    【讨论】:

    • 谢谢~这是另一个有用的点。但现在我只想提高输出而不是烦人的循环。如果没有直接的解决方案,我会留到时间。
    • 实际上不会有烦人的循环。只需导入 Decimal 并打印只需编写 print Decimal(ndarray[i]) 。不过这一切都取决于你:)
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2018-09-13
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多