「NumPy」astype()によるデータ型dtypeの変換サンプル
環境
Python3.9.2
PyCharm 2021.3.3
書式
ndarray.astype(dtype, order=’K’, casting=’unsafe’, subok=True, copy=True)
引数
dtype: str or dtype
order{‘C’, ‘F’, ‘A’, ‘K’}, optional
casting{‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional
subok:bool, optional
copy:bool, optional
NumPy配列ndarrayのメソッドastype()でデータ型dtypeを変換(キャスト)します。
dtypeが変更された新たなndarrayが生成され、元のndarrayは変化しない。
使用例
import numpy as np
cft = np.array([44, 255, 66])
print("配列の要素1")
print(cft)
print(cft.dtype)
print("astype()によるデータ型dtypeの変換")
resfloat = cft.astype(np.float32)
print(resfloat)
print(resfloat.dtype)
print("配列の要素2")
print(cft)
print(cft.dtype)
import numpy as np
cft = np.array([44, 255, 66])
print("配列の要素1")
print(cft)
print(cft.dtype)
print("astype()によるデータ型dtypeの変換")
resfloat = cft.astype(np.float32)
print(resfloat)
print(resfloat.dtype)
print("配列の要素2")
print(cft)
print(cft.dtype)
import numpy as np cft = np.array([44, 255, 66]) print("配列の要素1") print(cft) print(cft.dtype) print("astype()によるデータ型dtypeの変換") resfloat = cft.astype(np.float32) print(resfloat) print(resfloat.dtype) print("配列の要素2") print(cft) print(cft.dtype)
実行結果
配列の要素1
[ 44 255 66]
int32
astype()によるデータ型dtypeの変換
[ 44. 255. 66.]
float32
配列の要素2
[ 44 255 66]
int32
配列の要素1
[ 44 255 66]
int32
astype()によるデータ型dtypeの変換
[ 44. 255. 66.]
float32
配列の要素2
[ 44 255 66]
int32
配列の要素1 [ 44 255 66] int32 astype()によるデータ型dtypeの変換 [ 44. 255. 66.] float32 配列の要素2 [ 44 255 66] int32