Numpy常用屬性及方法

Numpy

一、屬性:

  1. ndarray.shape 返回一個元組,裏面是各個維度的size
  2. ndarray.ndim 返回數組的維度
  3. ndarray.dtype 返回數組數據的類型

二、方法:

  1. np.array(x, dtype=complex) 接收一個數組, dtype指定數據類型,
  2. np.zeros( (3,4) ) 接收一個代表數組維度size的元組
  3. np.ones((3,4)) 同上
  4. np.arange(10, 30, 5) 返回一個起始爲10,每次增加5,一直到30但不包括30的數組(本例返回[10, 15, 20, 25]),一般會跟reshape配合使用。
  5. np.linspace( 0, 2, 9 ) 將0-2分爲九份
  6. numpy.random.rand(d0, d1, ..., dn) Create an array of the given shape and populate it with random samples from a uniform distribution(均勻分佈) over [0, 1).
  7. numpy.random.randn(d0, d1, ..., dn) 功能與上面的類似,只不過randn是從標準正態分佈中取值,如果不傳入參數,則返回一個隨機的數(取自標準正態分佈)。要從

$$ N(\mu, \sigma^2) $$

中取值可以用這個公式sigma * np.random.randn(...) + mu

  1. a.ravel() # returns the array, flattened
  2. a.T # returns the array, transposed
  3. a.reshape(3,-1) If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated
  4. np.vstack((a,b))、np.hstack((a,b))
  5. numpy.concatenate((a1, a2, ...), axis=0, out=None) Join a sequence of arrays along an existing axis. 按照指定的axis進行連接

13.np.hsplit(a,(3,4)) # Split a after the third and the fourth column;類似的還有np.vsplit,這個是按行拆分,上面是按列拆分;

14.

運算:

  1. a+b a-b a*b 都是elementwise 運算;
  2. a.dot(b) 矩陣相乘運算;
  3. np.sin(a) 對矩陣a中的元素進行三角函數運算(類似的np.exp(a)、 np.sqrt(a));
  4. a**2 冪運算
  5. a<2 不等式運算。返回布爾值組成的數組,shape與a相同;
  6. a.sum() a.min() a.max(),三者都可接收一個axis作爲參數,返回特定axis的sum、min、max

Indexing, Slicing and Iterating

  1. a[:6:2] = -1000 # equivalent to a[0:6:2] = -1000; from start to position 6, exclusive, set every 2nd element to -1000(從開始到位置6,但不包括a[6],然後往前每隔一個設爲-1000)
  2. a[ : :-1] # reversed a,將a進行反轉。a是一維數組。
  3. 對於多維數組
    for row in b: row是每一行。
    for element in b.flat: element是每個元素。

Copies and Views

有三種情況:

  1. No Copy at All,比如b=a,b只是a的引用,不會有新的object被創建,b is a 會返回True
  2. View or Shallow Copy,比如c = a.view(),c is a返回False,但是c.base is a會返回True,c的值改變,會引起a的值改變,但是c的shape改變,不會引起a的shape改變;
  3. Deep Copy,比如 d = a.copy(),d is a 與d.base is a 都會返回False,d是一個全新的對象,與a沒有任何關係,d的改變不會引起a的改變。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章