type,dtype,astype的区别
type():返回数据结构的类型(list,dict等)。如type([1,2,3,4])返回list。list中可以包含不同数据类型的元素。
dtype():返回数据结构中数据元素的类型。因此要求数据结构中包含的数据元素结构相同,故list,dict等不能调用dtype。np.array()要求数据元素结构相同,可以调用dtype().如np.array([1,2,3]).dtype返回int32.
astype():改变np.array()中数据元素的数据类型。np.array([1,2,3]).astype(np.float).将数据元素改成float类型。备注:改变np.array的数据元素的数据类型只能用astype().不能通过赋值的形式np.array([1,2,3]).dtype=np.float.这样会改变array的长度。
使用标量类型
import numpy as np
dt = np.dtype('int32')
# int8, int16, int32, int64 四种数据类型可以使用字符串 'i1', 'i2','i4','i8' 代替
dt = np.dtype('i4')
print(dt)
#输出
#int32
结构化数据类型
import numpy as np
student = np.dtype([('name','S40'),('age','int32'),('marks','f4')])
a = np.array([('sun',28,65),('wang',21,60),('zhu',28,40)],dtype=student)
print(a)
#array([(b'sun', 28, 65.), (b'wang', 21, 60.), (b'zhu', 28, 40.)],
dtype=[('name', 'S40'), ('age', '
print(a['name'])
#array([b'sun', b'wang', b'zhu'], dtype='|S40')
引用