Python中dtype、type()和astype()的区别详解
Python中dtype、type()和astype()的区别
(1)type()是python内置的函数。type() 返回数据结构类型(list、dict、numpy.ndarray 等)
(2)dtype 返回数据元素的数据类型(int、float等)
(3)astype() 改变np.array中所有数据元素的数据类型。
备注:
1)由于 list、dict 等可以包含不同的数据类型,因此没有dtype属性
2)np.array 中要求所有元素属于同一数据类型,因此有dtype属性
能用dtype() 才能用 astype()
l1 = [1,2,4] ar1 = np.array(l1) print(type(l1)) #<class 'list'> print(l1.dtype) #会报错

ar1 = np.array(l1) print(type(a1)) #<class 'list'> print(ar1.dtype) #会报错

注意下面的例子
ar1 = np.array(l1) t1 = torch.from_numpy(ar1) print(type(a1)) #<class 'numpy.ndarray'> print(ar1.dtype) #int32 #注意print(ar1.type())会报错 print(t1.type()) #torch.IntTensor print(type(t1)) #<class 'torch.Tensor'> print(t1.dtype) #torch.int32

#a.astype(dtype) a不变 #返回Copy of the array, cast to a specified type. ar1 = np.arange(10,dtype=float) ar2 = ar1.astype(np.int) print(ar1,ar1.dtype) print(ar2,ar2.dtype)

到此这篇关于Python中dtype、type()和astype()的区别详解的文章就介绍到这了,更多相关Python的dtype、type()和astype()内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Python Setuptools的 setup.py实例详解
setup.py是一个 python 文件,它的存在表明您要安装的模块/包可能已经用 Setuptools 打包和分发,这是分发 Python 模块的标准。 它的目的是正确安装软件,本文给大家讲解Python Setuptools的 setup.py感兴趣的朋友跟随小编一起看看吧2022-12-12
python使用matplotlib的savefig保存时图片保存不完整的问题
这篇文章主要介绍了python使用matplotlib的savefig保存时图片保存不完整的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-01-01


最新评论