一起学数据分析之NumPy(2)——数据类型

dtype是一个特殊的对象,它含有ndarray将一块内存解释特定数据类型所需的信息:

<code> import numpy as np
 arr1 = np.array([1, 2, 3], dtype=np.float64)
 arr2 = np.array([1, 2, 3], dtype=np.int32)/<code>
<code> arr1.dtype/<code>
<code> dtype('float64')/<code>
<code> arr2.dtype/<code>
<code> dtype('int32')/<code>
<code> # 使用astype函数显示转换ndarray的dtype
 # 整数转换成浮点数
 arr = np.array([1, 2, 3, 4, 5])
 arr.dtype/<code>
<code> dtype('int32')/<code>
<code> float_arr = arr.astype(np.float64)
 float_arr.dtype/<code>
<code> dtype('float64')/<code>
<code> # 浮点数转换成整数
 arr = np.array([1.3, 2.3, -5.6, -7.8, 9.4 ])
 arr/<code>
<code> array([ 1.3,  2.3, -5.6, -7.8,  9.4])/<code>
<code> arr.dtype/<code>
<code> dtype('float64')/<code>
<code> arr.astype(np.int32)/<code>
<code> array([ 1,  2, -5, -7,  9])/<code>
<code> arr.dtype
 # 注意:浮点数转换成整数,会截断小数部分/<code>
<code> dtype('float64')/<code>
<code> # 如果字符串数组元素全部都是数字,也可以用astype将其转换为数值表示: 

 numeric_strings = np.array(['1.2', '4.5', '4', '6.4', '9'], dtype=np.string_)/<code>
<code> numeric_strings.astype(np.float64)/<code>
<code> array([1.2, 4.5, 4. , 6.4, 9. ])/<code>
<code> # 你也可以偷懒直接写成这样
 numeric_stings.astype(float)/<code>
<code> array([1.2, 4.5, 4. , 6.4, 9. ])/<code>
<code> # dtype还可以直接引用赋值,举个例子:
 int_array = np.arange(10)
 calibers = np.array([.22, .270, .357, .380, .44, .50], dtype=np.float64)
 # 我想把int_array的dtype变成跟calibers一样可以直接赋值
 int_array.astype(calibers.dtype)/<code>
<code> array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])/<code>
<code> # 你也可以用简洁的类型代码来表示dtype,u指unit,8指8字节
 empty_unit32 = np.empty(8, dtype='u8')
 empty_unit32/<code>
<code> array([   0,    0,    0,    0,    0, 1104,    0,    0], dtype=uint64)/<code>
<code> # 但是注意,调用astype会创建一个新的数组(拷贝),及时新数组跟老数组的dtype相同也是如此。
 # 数据类型对于大数据集的存储和计算尤为重要,但是通常来说,你只要把它当成还是普通的Python对象就行,大致类型无非就是浮点、复数、整数、布尔、字符串等。/<code>

dtype 是NumPy如此强大和灵活的原因之一。数值型dtype的命名方式相同:一个类型名(float,int等),后面跟一个用于表示各元素长的数字。 NumPy的数据类型这里不做更多的说明,有兴趣的读者可以自己查询。


分享到:


相關文章: