前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中dtype、type()、astype()区别

python中dtype、type()、astype()区别

作者头像
全栈程序员站长
发布2022-08-15 21:01:44
4000
发布2022-08-15 21:01:44
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

(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()

代码语言:javascript
复制
l1 = [1,2,4]
ar1 = np.array(l1)
print(type(l1)) #<class 'list'>
print(l1.dtype) #会报错
在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
ar1 = np.array(l1)
print(type(a1)) #<class 'list'>
print(ar1.dtype) #会报错
在这里插入图片描述
在这里插入图片描述

注意下面的例子

代码语言:javascript
复制
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
在这里插入图片描述
在这里插入图片描述
代码语言:javascript
复制
#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)
在这里插入图片描述
在这里插入图片描述

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/134321.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年5月2,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档