Numpy の型変換についてです。
astype
Numpy の ndarray 配列のデータをキャストする場合、astype を使います。たとえば、文字列として読み込んだデータを計算に使いたければ、astype(int)やastype(float)で型変換してから計算します。
1 2 3 4 5 6 7 8 |
import numpy as np list_s = np.array(['1', '2', '3', '4', '5']) list_s.astype(np.int) + 100 #---------------------------------- # array([101, 102, 103, 104, 105]) #---------------------------------- |
astype を指定せずに計算させると、もちろんエラーになります。
数値型の配列として持ちなおす場合も astype を使います。
1 |
list_i = list_s.astype(np.int) |
dtype
最初から int で持ちたければ、配列生成時にdtypeを指定します。
1 2 3 4 5 6 |
str = ['1', '2', '3', '4', '5'] list_i = np.array(str, dtype=np.int) #------------------------ # array([1, 2, 3, 4, 5]) #------------------------ |
dtype というのは ndarray 配列の属性で、配列内のデータ型を表します。
1 2 3 4 |
print (list_i.dtype) #-------- # int32 #-------- |