NumPyの使い方(2) データ型
NumPyのデータ型
dtype | 略号 | 種類 | |
int32 | i, i4 | 符号あり整数 | 32bit |
unit32 | I, u4 | 符号なし整数 | 32bit |
float32 | f, f4 | 小数 | 64bit |
complex64 | F, c8 | 複素数 | 128bit |
bool | 真偽値 | True, False | |
object | O | pythonオブジェクト | |
string | バイト文字列型 | 固定長。5文字なら'S5'など | |
unicode | ユニコード文字列型 | 'U10'など。日本語を扱う時 |
ビット数を指定できる型
データ | 種類 |
符号あり整数 | int8~int64 |
符号なし整数 | unit8~64 |
小数 | float~128 |
複素数 | complex64~256 |
略語もいろいろありそうだけど、覚えられなそう
型変換(cast)
np.astype()で変換する型を指定する。
データがコピーされ、新規オブジェクトが作られる。
小数を整数に型変換するときは原点方向に丸められる。
型変換不可能なときはValueErrorが発生。
a1 = np.array([1, 3, 5]) print(a1.dtype) # int32 # 符号なし整数へ型変換 a2 = a1.astype(np.uint32) print(a2.dtype) # unit32 a3 = np.array([-1.5, -0.8, 1.5, 2.1, 3.9]) print(a3.dtype) # float64 # 整数へ型変換すると原点方向へ丸め a3 = a3.astype(np.int32) print(a3) # [-1 0 1 2 3] a4 = np.array(["赤", "青", "緑"]) print(a4.dtype) # <U1 ユニコード文字列型 print(a4) # ['赤' '青' '緑'] #a4 = a4.astype(np.float64) # ValueError: could not convert string to float: '赤' # 既に存在している他のndarrayオブジェクトと同一の型を指定できる a5 = np.array([3.6, 1.8]) a5 = a5.astype(a1.dtype) print(a5.dtype) # int32
・ndarray生成時にdtypeを指定できる。
a1 = np.array([1, 3, 5], dtype=np.uint32) print(a1.dtype) # unit32