【numpy學習筆記】 Array processing

Datawhale發表於2018-07-11

1. numpy where function

>>>A = np.array([1,2,3,4])
>>>B= np.array([5,1,7,2])
>>>condition = np.array([True,False,False,False])
>>>np.where(condition,A,B)
array([1, 1, 7, 2])

>>>np.where(condition,B,A)
array([5, 2, 3, 4])
>>>b = np.random.randn(5,5)
array([[-0.2340034 , -1.03169723, -0.68866699, -0.95395849, -0.81065019],
       [ 1.57470122,  0.48663041,  0.69880676, -0.05555963, -0.84871411],
       [ 0.1612104 , -0.93401571,  0.04913108, -0.86189833,  1.61949843],
       [-0.92598677,  0.94459784,  0.23021928, -0.74052632,  0.29827747],
       [-0.34973875, -0.00318771,  0.48310484, -0.14342912,  1.04019596]])
>>>np.where(b < 0,0,b)  #change negative number to 0
array([[0.        , 0.        , 0.        , 0.        , 0.        ],
       [1.57470122, 0.48663041, 0.69880676, 0.        , 0.        ],
       [0.1612104 , 0.        , 0.04913108, 0.        , 1.61949843],
       [0.        , 0.94459784, 0.23021928, 0.        , 0.29827747],
       [0.        , 0.        , 0.48310484, 0.        , 1.04019596]])

2. Some Statistical Processing

>>>c = np.array([[1,2,3],[4,5,6],[7,8,9]])
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>>c.sum()
45
>>>c.sum(axis=1)
array([ 6, 15, 24])
>>>c.mean()
5.0
>>>c.std() #求標準差
2.5819888974716112
>>>c.var() #Returns the variance of the array elements, along given axis. 求方差
6.666666666666667

3. Array Sort

>>>d = np.random.randn(10)
array([-1.58417256,  0.16156529,  1.74941204, -0.75928321,  0.16414657,
        0.16228104,  1.08465636,  0.15334062, -1.90844477,  0.57501987])
>>>d.sort()
array([-1.03442217, -1.02168667,  0.04353088,  0.14622849,  0.2740999 ,
        0.2748698 ,  0.48825946,  0.6764689 ,  1.13611964,  1.18354015])
# in1d test values in one array
>>>e = np.array([1,2,3,3,4,4,5])
>>>np.in1d([2,4,8],e)
array([ True,  True, False], dtype=bool)
# 注意是數字1
# check if element in the first array appears in the second array

>>>np.unique(e) #Find the unique elements of an array.
array([1, 2, 3, 4, 5])

相關文章