1 回答

TA貢獻1844條經(jīng)驗 獲得超8個贊
您的問題非常不清楚,我相信您對 numpy 的工作原理感到困惑。如果是這樣,讓我們解釋一些事情。來自 numpy 的數(shù)組只不過是內(nèi)存中的一串字節(jié)。特別是,當為您顯示這些字節(jié)時,它們由 dtype 解釋。dtype 不用于存儲底層數(shù)據(jù),而僅用于顯示它。因此,更改 dtype 只會更改數(shù)據(jù)對您的外觀,不會更改數(shù)據(jù)本身。尺寸也是一樣。數(shù)據(jù)的維度只會改變數(shù)據(jù)的顯示和訪問方式,python 實際上并不會移動數(shù)據(jù)或改變數(shù)據(jù)本身。例如,
import numpy as np
x = np.array([[1,2,3],[4,5,6]],dtype='int64') #48 bytes, each int takes up 8 bytes.
print(x)
x.dtype = 'int32'
print(x)
x.dtype = 'float'
print(x)
x.dtype = 'int16'
print(x)
請注意,我們可以更改 dtype 并且絕對零計算由數(shù)組完成(因為基礎數(shù)據(jù)已經(jīng)是一個字節(jié)數(shù)組)。同樣,我們可以改變形狀,也可以完成絕對零計算。
x.shape = (2,2,6)
print(x)
shape 和 dtype 與內(nèi)存中存儲的數(shù)據(jù)無關。希望這可以清楚地說明我們現(xiàn)在如何將數(shù)組作為字節(jié)處理。
x = np.array([[1,2,3],[4,5,6]],dtype='int64')
print(x)
y = x.tobytes()
# Send y somewhere. Save to a file. Etc.
z = np.frombuffer(y)
z.dtype = 'int64'
z.shape = (2,3)
print(z)
添加回答
舉報