Python中dtype、type()和astype()的區(qū)別詳解
Python中dtype、type()和astype()的區(qū)別
(1)type()是python內(nèi)置的函數(shù)。type() 返回數(shù)據(jù)結(jié)構(gòu)類型(list、dict、numpy.ndarray 等)
(2)dtype 返回數(shù)據(jù)元素的數(shù)據(jù)類型(int、float等)
(3)astype() 改變np.array中所有數(shù)據(jù)元素的數(shù)據(jù)類型。
備注:
1)由于 list、dict 等可以包含不同的數(shù)據(jù)類型,因此沒有dtype屬性
2)np.array 中要求所有元素屬于同一數(shù)據(jù)類型,因此有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()的區(qū)別詳解的文章就介紹到這了,更多相關Python的dtype、type()和astype()內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python中numpy.zeros(np.zeros)的使用方法
下面小編就為大家?guī)硪黄猵ython中numpy.zeros(np.zeros)的使用方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-11-11
關于Python 實現(xiàn)tuple和list的轉(zhuǎn)換問題
這篇文章主要介紹了Python 實現(xiàn)tuple和list的轉(zhuǎn)換,文中介紹了list(列表)和tuple(元組)共同點和區(qū)別,結(jié)合實例代碼給大家介紹的非常詳細,需要的朋友可以參考下2023-05-05
簡單理解Python中的事件循環(huán)EventLoop
在 python 3中,加入了 asyncio 模塊,來實現(xiàn)協(xié)程,其中一個很重要的概念是事件循環(huán),本文我們就來自己實現(xiàn)一個相對簡單的EventLoop,從而了解一下事件循環(huán)是如何進行運轉(zhuǎn)的吧2023-10-10
Python技法之如何用re模塊實現(xiàn)簡易tokenizer
當我們在Python中開始新的東西時,我通常首先看一些模塊或庫來使用,下面這篇文章主要給大家介紹了關于Python技法之如何用re模塊實現(xiàn)簡易tokenizer的相關資料,需要的朋友可以參考下2022-05-05

