1. 程式人生 > >numpy常用函式筆記

numpy常用函式筆記

1. np.log10()

計算以10為底的對數值

import numpy as np
np.log10(x)

>>>np.log10(100)
2.0

2. np. log()

計算以e為底的對數值

import numpy as np
np.log(x)

>>>np.log(np.e)
1.0
>>>np.log(10)
2.3025850929940459

3. np.log2()

計算以2為底的對數值,直接把2放在log和()之間

import numpy as np
np.log2(x)

>>>np.log2(4)
2.0

4. np.random.shuffle(x)

將給定的陣列的內容進行重新排序(類似於洗牌,打亂順序)

arr=np.arange(10)
np.random.shuffle(arr)
>>>arr
array([5, 2, 7, 0, 6, 3, 4, 1, 8, 9])

#多維
arr=np.arange(12).reshape(3,4)
>>>arr
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

np.random.shuffle(arr)
>>>arr
array([[ 4,  5,  6,  7],
       [ 0,  1,  2,  3],
       [ 8,  9, 10, 11]])

5. np.mean()

功能:求平均值

通式:numpy.mean(a,axis,dtype,out,keepdims)

常用的引數:axis

eg:  m*n的矩陣

  • 不設定axis:對m*n個值求平均
  • axis=0:對每一列求平均值
  • axis=1:對每一行求平均值
>>>import numpy as np
>>>a=np.array([[1,2],[3,4])
>>>a
array([[1,2],
    [3,4]])

>>>np.mean(a)
2.5
>>>np.mean(a,axis=0)
array([2.0,3.0])
>>>np.mean(a,axis=1)
array([1.5,3.5])
>>>import numpy as np
>>>a=array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
>>>a
array([
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [10,11,12]])
>>>b=np.mat(a)
>>>b
matrix([
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [10,11,12]])

>>>np.mean(b)
6.5
>>>np.mean(b,0)
matrix[[5.5,6.5,7.5]]
>>>np.mean(b,1)
matrix[[2.0],
    [5.0],
    [8.0],
    [11.0]]

6. np.random. choice()

從一個int數字或1維array裡隨機選取內容

通式:np.random.choice(a, size=None, replace=True, p=None)

>>>import numpy as np
>>>np.random.choice(5,3)#從0-4五個數中任取三個
array([0,3,4])

>>>np.random.choice(5,3,p=[0.1,0,0.3,0.6,0])#從0-4五個數中以概率p隨機取三個
array=([3,3,0])

>>>np.random.choice(5,3,replace=False,p=[0.1,0,0.3,0.6,0])#從0-4五個數中不重複的以概率p隨機取三個
array([2,3,0])

未完待續