数据类型,即dytpe,是一个特殊的对象,它包含了ndarray需要为某一种类型数据所申明的内存块信息(也称为元数据,即表示数据的数据):
import numpy as np
arr1 = np.array([1,2,3],dtype = np.float64)
arr2 = np.array([1,2,3],dtype = np.int32)
arr1.dtype
dtype('float64')
arr2.dtype
dtype('int32')
dtype是Numpy能够与其他系统数据灵活交互的原因。
你可以使用astype方法显式地转换数组的数据类型:
arr = np.array([1,2,3,4,5])
arr.dtype
dtype('int32')
float_arr = arr.astype(np.float64)
float_arr.dtype
dtype('float64')
在上面例子中,整数被换成了浮点数。如果我把浮点数转换成整数,则小数点后的部分将被消除:
arr = np.array([3.7,-1.2,-2,6,0.5,12.9,10.1])
arr
array([ 3.7, -1.2, -2. , 6. , 0.5, 12.9, 10.1])
arr.astype(np.int32)
array([ 3, -1, -2, 6, 0, 12, 10])
如果你有一个数组,里面的元素都是表达数字含义的字符串,也可以通过astype将字符串转换为数字:
arr3 = np.array(['1.25','-9.6','42'],dtype = np.string_)
arr3.astype(float)
array([ 1.25, -9.6 , 42. ])
(在Numpy中,当使用 numpy.string_类型作字符串数据要小心,因为Numpy会修正它的大小或删除输入且不发出警告。pandas在处理非数值数据时有更直观的开箱型操作)
如果因为某些原因导致转换类型失败(比如字符串无法转换为float64位时),将会抛出一个ValueError。这里我偷懒地使用float来替代np.float64,是因为Numpy可以使用相同别名来表征于Python精度相同的Python数据类型。
你也可以使用另一个数组的dtype属性:
int_array = np.arange(10)
calibers = np.array([.22,.270,.357,.380,.44,.50],dtype = np.float64)
int_array.astype(calibers.dtype)
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
也可以使用类型代码来传入数据类型:
empty_uint32 = np.empty(8,dtype = 'u4')
empty_uint32
empty_uint32
empty_uint32
array([1324770695, 805393421, 1599436526, 1645630477, 1745310583,
1825934317, 1801670157, 805468270], dtype=uint32)
(使用astype时总是生成一个新的数组,即使你传入的dtype与之前一样。)
下列是Numpy所支持的数据类型:
- int8,uint8(i1,u1) :有符号和无符号的8数位整数
- int16,uint16(i2,u2) :有符号和无符号的16数位整数
- int32,uint32(i4,u4) :有符号和无符号的32数位整数
- int64,uint64(i8,u8) :有符号和无符号的64数位整数
- float16(f2) :半精度浮点数
- float32(f4或f) :标准单精度浮点数;兼容C语言float
- float64(f8或d) :标准单精度浮点数;兼容C语言double和Python float
- float128(f16或g) :拓展精度浮点数
- comple ×64,(c8,c16,c32) :分别基于32位、64位、128位浮点数的复数
comple ×128,
comple ×256 - bool(?) :布尔值,储存True或False
- object(O) :Python object类型
- string_(S) :修正的ASC ll字符串类型;例如生成一个长度为10的字符串类型,使用‘S10’
- unicode_(U) :修正的Unicode类型;例如生成一个长度为10的Unicode类型,使用‘U10’
(不需要担心如何记住Numpy的数据类型,尤其是当你还是新手的时候。通常只需要关心数据的大类,例如浮点型。整数。布尔值等。当你需要在内存或硬盘上做更深入的存取操作时,尤其是大数据集时,你才需要真正的了解存储的数据类型。)