python 中 dtype、type 和 asype 的区别
最编程
2024-03-16 17:36:10
...
(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 请求包的请求函数中 params 和 data 的区别。
-
[Python] 关于 open 函数中 r 和 rb 的区别的详细解答。
-
在 python 中读写文件时,r、rt、rb 和 r+ 的区别
-
python 中 dtype、type 和 asype 的区别
-
python-isinstance 与 type 的用法和区别
-
Python 中的 a=a+b 和 a+=b 有什么区别?
-
Python 中 hashlib.sha1 和 hashlib.MD5 算法的区别
-
python 中 break、continue、exit 和传递终止循环的区别。
-
python 中 break、continue 和 pass 之间的区别。
-
标题:混淆概念详细解析:Python中类、对象、方法、函数和属性的区别和理解