在开始学习ndarray对象属性之前,我们先运行两个简单的代码。
arr1 = np.array([0,2,4]),dtype = np.float64)arr2 = np.array([0,2,4]),dtype = np.int32)print(arr1.dtype) #输出结果为dtype('float64')print(arr2.dtype) #输出结果为dype('int32')
在我们之前运行的Numpy数组代码中,在输出结果中经常看到“dtype = np.float64”的字样。dtype代表ndarray需要为某一种类型数据所申明的内存块信息。我们并不需要记住Numpy有多少数据类型,只需要关心是否是浮点型、整数、布尔值、字符串或者某个Python对象即可。
Numpy数据类型
Numpy常见的数据类型有以下几种:
| 数据类型 | 描述 |
|---|---|
| int16 | 有符号和无符号的16数位整数 |
| int32 | 有符号和无符号的32数位整数 |
| int64 | 有符号和无符号的64数位整数 |
| float16 | 半精度浮点数 |
| float32 | 标准单精度浮点数 |
| float64 | 标准双精度浮点数 |
| bool | 布尔值,存储True或False |
| object | Python Object类型 |
数据类型转换
np.astype函数接收Numpy数据类型变量,可以将Numpy数组的数据类型进行转换。
请抄写下方的代码,在右边的编辑框中运行。
arr1 = np.array([7,8,9])print(arr.dtype) #输出结果为dtype('int64')float_arr1 = arr1.astype('float')print(float_arr1.dtype) #输出结果为dtype('float64')
通过上面的代码,我们很容易把Numpy数组中的’int64’类型转化为’float64’类型。如果我们将’float64’转化为’int64’类型,小数点后面的部分会被消除。
arr2 = np.array([3.7,-1.2,-2.6,0.5,12,9,0.01])print(arr2.astype('int32')) #输出结果为 [ 3 -1 -2 0 12 9 0]
在Python基础语法中,我们可以通过int( )函数将一个字符串强制转为整数。使用np.astype,我们可以批量将字符串数组转为整数或者浮点型数组。
