假設我有以下數組(實際上它是一個KxNxM掩碼數組,其中存儲了1514764800個字段,如:np.ma.array(data,mask = mask,dtype = np.float32)):用掩碼和np來減少數組,並用它來計算
import numpy as np
data = np.random.random((3,4,4))
mask = np.zeros((3,4,4), dtype=bool)
mask[1,2,2] = 1
mask[2,2,2] = 1
mask[2,1,3] = 1
mask[:,2,0] = 1
使用面膜,我可以很容易地減少大的數據集,以有效的:
newdata = data[mask]
newdata
array([ 0.91336042, 0.78399595, 0.9466537 , 0.75347407, 0.8213428 ,
0.13172648])
爲了知道在該行/列,他們是第三維我可以使用:
pos = np.where(mask)
pos
(array([0, 1, 1, 2, 2, 2], dtype=int64),
array([2, 2, 2, 1, 2, 2], dtype=int64),
array([0, 0, 2, 3, 0, 2], dtype=int64))
該信息(「newdata」和「pos」)可以保存,我可以節省大量的內存和存儲空間。但是,如何計算例如數據[:,2,2](在原始數據中)的所有字段的平均值? 在我的情況下,newdata有〜5300000條目。
儘管有時候使用起來很棘手,你有沒有試過[Masked arrays](http://docs.scipy.org/doc/numpy/reference/maskedarray.html)? (我假定你的意思是你想計算不包含掩蔽值的平均值)。 – Iguananaut
我們的目標是將大陣列減少到有效陣列,保存它們的位置。我的數據存儲在掩碼數組中。但是,我想將大數組(np.float32〜1514764800個元素)減少爲僅考慮有效值的可用數據集。 – HyperCube
這基本上是掩碼數組的重點。您正在使用普通的'ndarray'並直接對其應用布爾掩碼,但在更新版本的Numpy中的'numpy.ma'模塊爲此具有特殊的'masked_array'類型。 – Iguananaut