Home > Article > Backend Development > Detailed explanation of Numpy masked arrays
The following is a detailed explanation of Numpy masked arrays, which has good reference value and I hope it will be helpful to everyone. Let’s take a look together
The data is often messy and contains blank or unprocessable characters. Masked arrays can ignore incomplete or invalid data points very well. The masked array consists of a normal array and a Boolean array. If the Boolean array is True, it means that the value corresponding to the subscript in the normal array is invalid. Otherwise, False means that the value corresponding to the normal array is valid.
The creation method is to first create a Boolean array, and then create a masked array through the functions provided by the numpy.ma subroutine package. The masked array provides various required functions.
Create an instance as follows:
import numpy as np origin = np.arange(16).reshape(4,4) #生成一个4×4的矩阵 np.random.shuffle(origin) #随机打乱矩阵元素 random_mask = np.random.randint(0,2,size=origin.shape)#生成随机[0,2)的整数的4×4矩阵 mask_array = np.ma.array(origin,mask=random_mask)#生成掩码式矩阵 print(mask_array)
The results are as follows:
[[12 13 -- 15] [8 9 10 --] [-- -- -- 3] [-- 5 6 --]]
is used for:
1. For negative numbers Take the logarithm
import numpy as np triples = np.arange(0,10,3)#每隔3取0到10中的整数,(0,3,6,9) signs = np.ones(10)#(1,1,1,1,1,1,1,1,1) signs[triples] = -1#(-1,1,1,-1,1,1,-1,1,1,-1) values = signs * 77#(-77,77,77,-77,77,77,-77,77,77,-77) ma_log = np.ma.log(values)#掩码式取对数 print(ma_log)
##The result is:
[-- 4.343805421853684 4.343805421853684 -- 4.343805421853684 4.343805421853684 -- 4.343805421853684 4.343805421853684 --]
2. Ignore extreme values
##import numpy as np inside = np.ma.masked_outside(array,min,max)
Related recommendations :
The above is the detailed content of Detailed explanation of Numpy masked arrays. For more information, please follow other related articles on the PHP Chinese website!