NumPy配列ndarrayの表示形式(桁数や指数表記、0埋めなど)を指定

Posted: | Tags: Python, NumPy

NumPy配列ndarrayprint()で出力する場合の表示形式(桁数や指数表記、0埋めなど)は、numpy.set_printoptions()で各パラメータを設定することで変更できる。

np.set_printoptions()による設定はあくまでもprint()で表示するときの設定で、元のndarray自体の値は変わらない。

ここでは以下の内容について説明する。

  • 現在の設定を確認: np.get_printoptions()
  • 小数点以下の桁数指定: precision, floatmode
  • 指数表記にする / しない: suppress
  • 各型に任意のフォーマットを指定: formatter
    • 小数点以下の桁数指定
    • 指数表記
    • 整数のゼロ埋め

同じくnp.set_printoptions()で、ndarrayの要素数が多い場合に省略するかどうかも設定できる。以下の記事を参照。

np.set_printoptions()による設定はJupyter Notebookで値を出力するときにも適用される。小数点以下の精度についてはマジックコマンド%precisionで指定することも可能。

現在の設定を確認: np.get_printoptions()

現在の設定はnp.get_printoptions()で確認できる。各パラメータの値が辞書dict形式となって返される。

import numpy as np

print(np.get_printoptions())
# {'edgeitems': 3, 'threshold': 1000, 'floatmode': 'maxprec', 'precision': 8, 'suppress': False, 'linewidth': 75, 'nanstr': 'nan', 'infstr': 'inf', 'sign': '-', 'formatter': None, 'legacy': False}

小数点以下の桁数指定(precision, floatmode)

precision

パラメータprecisionで小数点以下の桁数を指定する。

precisionは有効数字(有効桁数)ではなく小数点以下の桁数に対する設定。整数部には影響しない。

デフォルトはprecision=8

a = np.array([12.3456, 0.123456789])
print(a)
# [12.3456      0.12345679]

np.set_printoptions(precision=3)
print(a)
# [12.346  0.123]

np.set_printoptions(precision=10)
print(a)
# [12.3456       0.123456789]

floatmode

パラメータfloatmodeで小数点以下の表示形式を選択できる。

デフォルトはfloatmode=maxprec。それぞれの要素が必要な桁数で表示される。末尾はゼロで埋められない。

np.set_printoptions(precision=4, floatmode='maxprec')
print(a)
# [12.3456  0.1235]

np.set_printoptions(precision=10, floatmode='maxprec')
print(a)
# [12.3456       0.123456789]

floatmode=fixedは、すべての要素の桁数がprecisionの値で固定。末尾がゼロ埋めされる。

np.set_printoptions(precision=4, floatmode='fixed')
print(a)
# [12.3456  0.1235]

np.set_printoptions(precision=10, floatmode='fixed')
print(a)
# [12.3456000000  0.1234567890]

floatmode=maxprec_equalは、最大桁数の要素に合わせて他の要素はゼロ埋めされる。

np.set_printoptions(precision=4, floatmode='maxprec_equal')
print(a)
# [12.3456  0.1235]

np.set_printoptions(precision=10, floatmode='maxprec_equal')
print(a)
# [12.345600000  0.123456789]

floatmode=uniqueは、precisionの値に関わらず各要素が必要な桁数で表示される。

np.set_printoptions(precision=4, floatmode='unique')
print(a)
# [12.3456       0.123456789]

np.set_printoptions(precision=10, floatmode='unique')
print(a)
# [12.3456       0.123456789]

np.round()

上述のように、np.set_printoptions()による設定はprint()で表示するときの設定で、元のndarray自体の値は変わらないし、新たなndarrayが生成されることもない。

任意の桁数で丸めたndarrayを新たに生成したい場合はnp.round()を使う。第一引数に対象となるndarray、第二引数に小数点以下の桁数を指定する。桁数として負の値を使うと整数の桁で丸めることもできる。

b = np.round(a, 2)
print(b)
# [12.35  0.12]

b = np.round(a, -1)
print(b)
# [10.  0.]

b = np.round([1234.56, 123456.789], -2)
print(b)
# [  1200. 123500.]

指数表記にする / しない(suppress)

デフォルトではndarrayの最小値が1e-4(=0.0001)より小さい、または最大値と最小値の比率が1e3(=1000)より大きい場合に指数表記で表示される。

指数表記される場合はすべての要素が指数表記される。

a = np.array([0.123456, 0.123456])
print(a)
# [0.123456 0.123456]

a = np.array([0.123456, 0.0000123456])
print(a)
# [1.23456e-01 1.23456e-05]

a = np.array([123.456, 0.0123456])
print(a)
# [1.23456e+02 1.23456e-02]

np.set_printoptions()でパラメータsuppress=Trueとすると、指数表記を禁止にして常に小数で表示される。デフォルトはsuppress=False(指数表記あり)。

np.set_printoptions(suppress=True)
print(a)
# [123.456       0.0123456]

常に指数表記にしたい場合は、後述のformatterを使う。

なお、指数表記の場合、precisionfloatmodeの設定は仮数部に対して効く。

np.set_printoptions(suppress=True, precision=2)
print(a)
# [123.46   0.01]

np.set_printoptions(suppress=False, precision=2)
print(a)
# [1.23e+02 1.23e-02]

np.set_printoptions(suppress=False, precision=8, floatmode='fixed')
print(a)
# [1.23456000e+02 1.23456000e-02]

各型に任意のフォーマットを指定(formatter)

np.set_printoptions()でパラメータformatterfloatintなどの各型に対して適用される関数を辞書型で指定できる。

小数や整数などの数値にはフォーマット関数format()を使うと便利。format()についての詳細は以下の記事を参照。

floatに対しては、例えば.2f.8fで小数点以下の桁数を指定したり、.2e.8eで指数表記にして仮数部の小数点以下の桁数を指定したりできる。

np.set_printoptions(precision=8, floatmode='maxprec', suppress=False)

a = np.array([123.456, 0.0123456])
print(a)
# [1.23456e+02 1.23456e-02]

np.set_printoptions(formatter={'float': '{:.2f}'.format})
print(a)
# [123.46 0.01]

np.set_printoptions(formatter={'float': '{:.8f}'.format})
print(a)
# [123.45600000 0.01234560]

np.set_printoptions(formatter={'float': '{:.2e}'.format})
print(a)
# [1.23e+02 1.23e-02]

np.set_printoptions(formatter={'float': '{:.8e}'.format})
print(a)
# [1.23456000e+02 1.23456000e-02]

整数intに対しては、08dのように0埋めをしたり、2進数b、8進数o、16進数xに変換して表示したりできる。

a = np.array([12, 1234])
print(a)
# [  12 1234]

np.set_printoptions(formatter={'int': '{:08d}'.format})
print(a)
# [00000012 00001234]

np.set_printoptions(formatter={'int': '{:b}'.format})
print(a)
# [1100 10011010010]

np.set_printoptions(formatter={'int': '{:o}'.format})
print(a)
# [14 2322]

np.set_printoptions(formatter={'int': '{:x}'.format})
print(a)
# [c 4d2]

文字列メソッドを使って、文字列numpystrをすべて大文字にする、などの設定も可能。無名関数(ラムダ式)で任意の処理を行うこともできる。

a = np.array(['One', 'Two'])
print(a)
# ['One' 'Two']

np.set_printoptions(formatter={'numpystr': str.upper})
print(a)
# [ONE TWO]

np.set_printoptions(formatter={'numpystr': lambda x: '***' + x + '***'})
print(a)
# [***One*** ***Two***]

formatterの設定は辞書型でまとめて指定できる。常に使いたい設定があればスクリプトの最初に記述しておけばよい。

なお、floatintなどの型dtypeは各要素ではなくndarrayに対して設定されており、すべての要素にその型のformatterが適用される。

np.set_printoptions(formatter={'float': '{:0.8e}'.format, 'int': '{:08d}'.format})

a = np.array([12, 12.34])
print(a.dtype)
print(a)
# float64
# [1.20000000e+01 1.23400000e+01]

a = np.array([12, 123])
print(a.dtype)
print(a)
# int64
# [00000012 00000123]

関連カテゴリー

関連記事