Numpy數據類型對象(dtype)使用詳解


#記住引入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'), ('numitems', '<i4'), ('price','<f4')])
 
# 獲取字段類型
>>> t['name']
dtype('|S40')
 
# 使用記錄類型創建數組
# 否則它會把記錄拆開
>>> itemz = array([('Meaning of life DVD', 42, 3.14), ('Butter', 13,2.72)], dtype=t)
>>> itemz[1]
('Butter', 13, 2.7200000286102295)
#再舉個例*
>>>adt = np.dtype("a3, 3u8, (3,4)a10")  #3字節字符串、3個64位整型子數組、3*4的10字節字符串數組,注意8為字節
>>>itemz = np.array([('Butter',[13,2,3],[['d','o','g','s'],['c','a','t','s'],['c','o','w','s']])],dtype=adt)
>>>itemz
(b'But', [13,  2,  3], [[b'd', b'o', b'g', b's'], [b'c', b'a', b't', b's'], [b'c', b'o', 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, 12], [55, 56]])
>>> dt = np.dtype(('S10', 1))         # 10字符字符串
>>> dt = np.dtype(('i4, (2,3)f8, f4', (2,3))) # 2*3結構子數組
 
#[(field_name, field_dtype, field_shape), …]
>>> dt = np.dtype([('big', '>i4'), ('little', '<i4')])
>>> dt = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('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的子數組

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM