网站首页 > 基础教程 正文
dtype是一个特殊的对象,它含有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')
# 使用astype函数显示转换ndarray的dtype
# 整数转换成浮点数
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([1.3, 2.3, -5.6, -7.8, 9.4 ])
arr
array([ 1.3, 2.3, -5.6, -7.8, 9.4])
arr.dtype
dtype('float64')
arr.astype(np.int32)
array([ 1, 2, -5, -7, 9])
arr.dtype
# 注意:浮点数转换成整数,会截断小数部分
dtype('float64')
# 如果字符串数组元素全部都是数字,也可以用astype将其转换为数值表示:
numeric_strings = np.array(['1.2', '4.5', '4', '6.4', '9'], dtype=np.string_)
numeric_strings.astype(np.float64)
array([1.2, 4.5, 4. , 6.4, 9. ])
# 你也可以偷懒直接写成这样
numeric_stings.astype(float)
array([1.2, 4.5, 4. , 6.4, 9. ])
# 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)
array([0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])
# 你也可以用简洁的类型代码来表示dtype,u指unit,8指8字节
empty_unit32 = np.empty(8, dtype='u8')
empty_unit32
array([ 0, 0, 0, 0, 0, 1104, 0, 0], dtype=uint64)
# 但是注意,调用astype会创建一个新的数组(拷贝),及时新数组跟老数组的dtype相同也是如此。
# 数据类型对于大数据集的存储和计算尤为重要,但是通常来说,你只要把它当成还是普通的Python对象就行,大致类型无非就是浮点、复数、整数、布尔、字符串等。
dtype 是NumPy如此强大和灵活的原因之一。数值型dtype的命名方式相同:一个类型名(float,int等),后面跟一个用于表示各元素长的数字。 NumPy的数据类型这里不做更多的说明,有兴趣的读者可以自己查询。
猜你喜欢
- 2024-10-12 一文掌握Numpy矩阵 numpy矩阵乘法实现原理
- 2024-10-12 矩阵运算库:Numpy 矩阵运算库不支持点乘
- 2024-10-12 Python 的整数与 Numpy 的数据溢出
- 2024-10-12 整理20个Pandas统计函数 pandas函数汇总
- 2024-10-12 一文搞定Pandas核心概念之Series pandas的两大核心
- 2024-10-12 人工智能深度学习基础——Numpy模块知识汇总
- 2024-10-12 关于类型为numpy,TensorFlow.tensor,torch.tensor的shape变化
- 2024-10-12 Numpy基础用法汇总 numpy基础及取值操作
- 2024-10-12 想学好Python数据分析,一定要掌握的重要模块之numpy
- 2024-10-12 numpy基础之ndarray的数据类型dtype
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)