NumPy

NumPy

建議

  • 使用numpy時, 建議採用面向過程的思想, 由於numpy中對象有的, numpy模塊都會提供函數獲取到或者進行操做
  • 學會了MATLAB, 在NumPy中能夠找到不少MATLAB的影子

數組操做

數組的拼接與分割

  • np.concatenate((arr1, arr2), axis=1) # axis=1表示列優先, axis=0表示行優先, 它的功能和np.hstack和np.vstack同樣
  • np.split(arr, 2, axis=1) # axis表示列優先, axis=0表示行優先, 它的功能和np.hsplit和np.vsplit同樣, 返回list, 包含ndarray
  • 記憶方法: 列優先則是在水平方向放去拉伸數組, 行優先則是在豎直方向上去拉伸數組

其餘操做

  • np.reshape()
  • np.shape()
  • np.size()
  • np.diag()
  • np.eye()
  • np.zeros()
  • np.ones()

有用的

  • np.max()
  • np.min()
  • 以上返回的是指
  • np.argmax()
  • np.argmin()
  • 返回的是對應的值的下標
  • np.std()
  • np.mean()
  • np.var()
  • np.cumsum()
  • np.cumprod()
  • np.sum()

random模塊

  • np.random.rand(): 均勻分佈
  • np.random.randn(): 高斯分佈
  • np.random.uniform(): 生成[0, 1]範圍的均勻分佈
  • np.random.normal(): 高斯分佈

矩陣(是ndarray的子類)操做

  • 經過字符串的方式模仿MATLAB(可是仍是MATLAB使用起來更加方便)
  • mat = np.mat('1 2 3; 4 5 6') <=> np.matrix('1 2 3; 4 5 6', copy=False)
  • mat = np.matrix('[1 2 3; 4 5 6]', copy=True) # 建立一個矩陣
  • mat = np.bmat('arr1; arr2') # 經過兩個分塊矩陣建立一個新的矩陣, bmat是block matrix

ufunc

  • 在numpy中全部的符號運行都是調用了ufunc
    • +, -, *, /, **
  • 當兩個矩陣的shape一致時好理解, 可是當shape不同的時候, ufunc會採用廣播機制
    • 如:
      • arr1 = np.mat([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
      • arr2 = np.mat([1, 2, 3])
      • arr1 + arr2 ?
      • ufunc + 會將arr2的數據進行廣播生成一個[[1, 2, 3], [1, 2, 3], [1, 2, 3]]再參與運算

保存讀取數據

  • 保存數組(和MATLAB中的save同樣)
    • 二進制保存
      • np.save(filename, arr)
      • np.savez(filename, arr1, arr2, arr3) # 保存多個
    • 文本保存(更加經常使用)
      • np.savetxt(filename, arr, fmt='%d', delimeter=',') # 保存爲csv格式
  • 讀取數據
    • 二進制
      • np.load()
    • 文本
      • np.loadtxt()
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息