關於Numpy資料型別物件(dtype)使用詳解
阿新 • • 發佈:2020-01-09
常用方法
#記住引入numpy時要是用別名np,則所有的numpy字樣都要替換 #查詢數值型別 >>>type(float) dtype('float64') # 查詢字元程式碼 >>> dtype('f') dtype('float32') >>> dtype('d') dtype('float64') # 查詢雙字元程式碼 >>> dtype('f8') dtype('float64') # 獲取所有字元程式碼 >>> sctypeDict.keys() [0,… 'i2','int0'] # char 屬性用來獲取字元程式碼 >>> t = dtype('Float64') >>> t.char 'd' # type 屬性用來獲取型別 >>> t.type <type 'numpy.float64'> # str 屬性獲取完整字串表示 # 第一個字元是位元組序,< 表示小端,> 表示大端,| 表示平臺的位元組序 >>> t.str '<f8' # 獲取大小 >>> t.itemsize 8 # 許多函式擁有 dtype 引數 # 傳入數值型別、字元程式碼和 dtype 都可以 >>> arange(7,dtype=uint16) array([0,1,2,3,4,5,6],dtype=uint16)
型別引數及縮寫
型別 | 字元程式碼 |
---|---|
bool | ?,b1 |
int8 | b,i1 |
uint8 | B,u1 |
int16 | h,i2 |
uint16 | H,u2 |
int32 | i,i4 |
uint32 | I,u4 |
int64 | q,i8 |
uint64 | Q,u8 |
float16 | f2,e |
float32 | f4,f |
float64 | f8,d |
complex64 | F4,F |
complex128 | F8,D |
str | a,S(可以在S後面新增數字,表示字串長度,比如S3表示長度為三的字串,不寫則為最大長度) |
unicode | U |
object | O |
void | V |
自定義異構資料型別
基本書寫格式
import numpy #定義t的各個欄位型別 >>> t = dtype([('name',str,40),('numitems',numpy.int32),('price',numpy.float32)]) >>> t dtype([('name','|S40'),'<i4'),'<f4')]) # 獲取欄位型別 >>> t['name'] dtype('|S40') # 使用記錄型別建立陣列 # 否則它會把記錄拆開 >>> itemz = array([('Meaning of life DVD',42,3.14),('Butter',13,2.72)],dtype=t) >>> itemz[1] ('Butter',2.7200000286102295) #再舉個例* >>>adt = np.dtype("a3,3u8,(3,4)a10") #3位元組字串、3個64位整型子陣列、3*4的10位元組字串陣列,注意8為位元組 >>>itemz = np.array([('Butter',[13,3],[['d','o','g','s'],['c','a','t','w','s']])],dtype=adt) >>>itemz (b'But',[[b'd',b'o',b'g',b's'],[b'c',b'a',b't',b'w',b's']])
其他書寫格式
#(flexible_dtype,itemsize)第一個大小不固定的引數型別,第二傳入大小: >>> dt = np.dtype((void,10)) #10位 >>> dt = np.dtype((str,35)) # 35字元字串 >>> dt = np.dtype(('U',10)) # 10字元unicode string #(fixed_dtype,shape)第一個傳入固定大小的型別引數,第二引數傳入個數 >>> dt = np.dtype((np.int32,(2,2))) # 2*2int子陣列 舉例: >>>item = np.array([([12,12],[55,56])],dtype=dt) array([[12,56]]) >>> dt = np.dtype(('S10',1)) # 10字元字串 >>> dt = np.dtype(('i4,3)f8,f4',3))) # 2*3結構子陣列 #[(field_name,field_dtype,field_shape),…] >>> dt = np.dtype([('big','>i4'),('little','<i4')]) >>> dt = np.dtype([('R','u1'),('G',('B',('A','u1')]) #{‘names': …,‘formats': …,‘offsets': …,‘titles': …,‘itemsize': …}: >>> dt= np.dtype({'names':('Date','Close'),'formats':('S10','f8')}) >>> dt = np.dtype({'names': ['r','b'],'formats': ['u1','u1'],'offsets': [0,2],'titles': ['Red pixel','Blue pixel']}) #(base_dtype,new_dtype): >>>dt = np.dtype((np.int32,(np.int8,4))) //base_dtype被分成4個int8的子陣列
以上這篇關於Numpy資料型別物件(dtype)使用詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。