Numpy資料型別轉換astype,dtype

2021-08-21 03:26:08 字數 1080 閱讀 5297

in [11]: arr = np.array([1,2,3,4,5])

in [12]: arr

out[12]: array([1, 2, 3, 4, 5])

// 該命令檢視資料型別

in [13]: arr.dtype

out[13]: dtype('int64')

in [14]: float_arr = arr.astype(np.float64)

// 該命令檢視資料型別

in [15]: float_arr.dtype

out[15]: dtype('float64')

// 如果將浮點數轉換為整數,則小數部分會被截斷

in [7]: arr2 = np.array([1.1, 2.2, 3.3, 4.4, 5.3221])

in [8]: arr2

out[8]: array([ 1.1 , 2.2 , 3.3 , 4.4 , 5.3221])

// 檢視當前資料型別

in [9]: arr2.dtype

out[9]: dtype('float64')

// 轉換資料型別 float -> int

in [10]: arr2.astype(np.int32)

out[10]: array([1, 2, 3, 4, 5], dtype=int32)

in [4]: numeric_strings = np.array(['1.2','2.3','3.2141'], dtype=np.string_)

in [5]: numeric_strings

out[5]: array(['1.2', '2.3', '3.2141'], dtype='|s6')

// 此處寫的是float 而不是np.float64, numpy很聰明,會將python型別對映到等價的dtype上

in [6]: numeric_strings.astype(float)

out[6]: array([ 1.2, 2.3, 3.2141])

Numpy資料型別轉換astype,dtype

in 11 arr np.array 1,2,3,4,5 in 12 arr out 12 array 1,2,3,4,5 該命令檢視資料型別 in 13 arr.dtype out 13 dtype int64 in 14 float arr arr.astype np.float64 該命令檢視...

NumPy 資料型別

numpy 支援比 python 更多種類的數值型別。下表顯示了 numpy 中定義的不同標量資料型別。序號資料型別及描述 1.bool 儲存為乙個位元組的布林值 真或假 2.int 預設整數,相當於 c 的long,通常為int32或int64 3.intc相當於 c 的int,通常為int32或...

NumPy 資料型別

numpy提供的數值型別,數值範圍比python提供的數值型別更大。numpy的數值型別,如下表所示 sn資料型別描述1 bool 布林值,取值ture false,占用乙個位元組 2int 是integer的預設型別。與c語言中的long型別相同,有可能是64位或32位。3intc 類似於c語言中...