Python print numpy array 設定精準度

本篇紀錄如何使用 Python print numpy array 設定精準度。

Python print numpy array 設定精準度

以下範例示範 Python print numpy array 設定精準度,第一個 arr1 是隨機產生 3 個數值,第二個 arr2 是指定各種數值並且有一些是含科學符號的數值,使用 np.printoptions() 設定 precision 參數可以控制印出的精準度,如果不想要影響全域結果可以使用區域的寫法 with np.printoptions(...): (需要 NumPy 1.15.0 或以後的版本),

python3-numpy-print-array-precision.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np

arr1 = np.random.random(3)
print(arr1)
#np.printoptions(precision=2)
with np.printoptions(precision=2, suppress=True):
print(arr1)
print(arr1)

arr2 = np.asarray([1.5e-10, 1.5, 1500])

print(type(arr2)) # <class 'numpy.ndarray'>
print(arr2)
#np.printoptions(precision=2)
with np.printoptions(precision=2, suppress=True):
print(arr2)
print(arr2)

輸出如下,

1
2
3
4
5
6
7
[0.99005858 0.2245673  0.5895889 ]
[0.99 0.22 0.59]
[0.99005858 0.2245673 0.5895889 ]
<class 'numpy.ndarray'>
[1.5e-10 1.5e+00 1.5e+03]
[ 0. 1.5 1500. ]
[1.5e-10 1.5e+00 1.5e+03]

其他參考
python - How to pretty-print a numpy.array without scientific notation and with given precision? - Stack Overflow
https://stackoverflow.com/questions/2891790/how-to-pretty-print-a-numpy-array-without-scientific-notation-and-with-given-pre

其它相關文章推薦
如果你想學習 Python 相關技術,可以參考看看下面的文章,
Python 新手入門教學懶人包
Python str 字串用法與範例
Python list 串列用法與範例
Python set 集合用法與範例
Python dict 字典用法與範例
Python tuple 元組用法與範例