NumPy配列ndarrayの要素を絶対値に変換するnp.abs
NumPy配列ndarray
の要素を絶対値に変換するには、np.abs()
やnp.absolute()
, np.fabs()
を使う。np.abs()
はnp.absolute()
のエイリアス。組み込み関数abs()
も利用できる。
バージョン1.26.2時点ではndarray
のメソッドとしては提供されていない。
本記事のサンプルコードのNumPyのバージョンは以下の通り。バージョンによって仕様が異なる可能性があるので注意。
import numpy as np
print(np.__version__)
# 1.26.2
np.abs()とnp.absolute()の使い方
np.abs()はnp.absolute()のエイリアス
np.abs()
はnp.absolute()
のエイリアス。
print(np.abs)
# <ufunc 'absolute'>
print(np.abs is np.absolute)
# True
以降のサンプルコードではnp.abs()
を使うが、np.absolute()
も同じように使える。
基本的な使い方
np.abs()
の引数にndarray
を指定すると、各要素が絶対値に変換されたndarray
が返される。
a = np.array([-2, -1, 0, 1, 2])
print(np.abs(a))
# [2 1 0 1 2]
print(type(np.abs(a)))
# <class 'numpy.ndarray'>
np.abs()
にはndarray
だけでなくリストなどのarray-likeオブジェクトも指定可能。ただし、返り値はndarray
。
l = [-2, -1, 0, 1, 2]
print(np.abs(l))
# [2 1 0 1 2]
print(type(np.abs(l)))
# <class 'numpy.ndarray'>
ndarray
とリストの相互変換については以下の記事を参照。
np.abs()
にはスカラー値を指定することもできる。
print(np.abs(-100))
# 100
print(type(np.abs(-100)))
# <class 'numpy.int64'>
intならint、floatならfloatを返す
np.abs()
の引数に指定したndarray
のデータ型dtype
が整数int
なら整数int
、浮動小数点数float
なら浮動小数点数float
のndarray
が返される。
a_int = np.array([-2, -1, 0, 1, 2])
print(a_int.dtype)
# int64
print(np.abs(a_int))
# [2 1 0 1 2]
print(np.abs(a_int).dtype)
# int64
a_float = np.array([-2.0, -1.0, 0, 1.0, 2.0])
print(a_float.dtype)
# float64
print(np.abs(a_float))
# [2. 1. 0. 1. 2.]
print(np.abs(a_float).dtype)
# float64
NumPyにおけるデータ型dtype
についての詳細は以下の記事を参照。
複素数にも対応
Pythonでは虚数単位をj
として複素数complex
を扱える。
np.abs()
は複素数complex
も絶対値(大きさ、複素数平面における原点からの距離)に変換する。絶対値が整数であっても返り値のデータ型は浮動小数点数float
。
a_complex = np.array([3 + 4j, 5 + 12j])
print(a_complex.dtype)
# complex128
print(np.abs(a_complex))
# [ 5. 13.]
print(np.abs(a_complex).dtype)
# float64
NumPy配列ndarrayに対する組み込み関数abs()
ndarray
には特殊メソッド__abs__()
が定義されており、Pythonの組み込み関数abs()
の引数に指定可能。
a = np.array([-2, -1, 0, 1, 2])
print(a.__abs__())
# [2 1 0 1 2]
print(abs(a))
# [2 1 0 1 2]
print(type(abs(a)))
# <class 'numpy.ndarray'>
ndarray
に対して、abs()
はnp.absolute()
(= np.abs()
)と同じように使える。
The
abs
function can be used as a shorthand fornp.absolute
on ndarrays. numpy.absolute — NumPy v1.26 Manual
np.abs()
と同様に複素数complex
にも対応する。
a_complex = np.array([3 + 4j, 5 + 12j])
print(abs(a_complex))
# [ 5. 13.]
np.fabs()とnp.abs()の違い
np.fabs()
はnp.abs()
と同様にndarray
の要素を絶対値に変換するが、返り値のデータ型は常に浮動小数点数float
。整数int
に対しても浮動小数点数float
を返す。
a_int = np.array([-2, -1, 0, 1, 2])
print(a_int.dtype)
# int64
print(np.fabs(a_int))
# [2. 1. 0. 1. 2.]
print(np.fabs(a_int).dtype)
# float64
math.fabs()
は実数にのみ対応し、複素数complex
に対してはエラーとなる。
a_complex = np.array([3 + 4j, 5 + 12j])
# print(np.fabs(a_complex))
# TypeError: ufunc 'fabs' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''