Numpy
一、屬性:
- ndarray.shape 返回一個元組,裏面是各個維度的size
- ndarray.ndim 返回數組的維度
- ndarray.dtype 返回數組數據的類型
二、方法:
- np.array(x, dtype=complex) 接收一個數組, dtype指定數據類型,
- np.zeros( (3,4) ) 接收一個代表數組維度size的元組
- np.ones((3,4)) 同上
- np.arange(10, 30, 5) 返回一個起始爲10,每次增加5,一直到30但不包括30的數組(本例返回[10, 15, 20, 25]),一般會跟reshape配合使用。
- np.linspace( 0, 2, 9 ) 將0-2分爲九份
- 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).
- numpy.random.randn(d0, d1, ..., dn) 功能與上面的類似,只不過randn是從標準正態分佈中取值,如果不傳入參數,則返回一個隨機的數(取自標準正態分佈)。要從
$$ N(\mu, \sigma^2) $$
中取值可以用這個公式sigma * np.random.randn(...) + mu
- a.ravel() # returns the array, flattened
- a.T # returns the array, transposed
- a.reshape(3,-1) If a dimension is given as -1 in a reshaping operation, the other dimensions are automatically calculated
- np.vstack((a,b))、np.hstack((a,b))
- 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.
運算:
- a+b a-b a*b 都是elementwise 運算;
- a.dot(b) 矩陣相乘運算;
- np.sin(a) 對矩陣a中的元素進行三角函數運算(類似的np.exp(a)、 np.sqrt(a));
- a**2 冪運算
- a<2 不等式運算。返回布爾值組成的數組,shape與a相同;
- a.sum() a.min() a.max(),三者都可接收一個axis作爲參數,返回特定axis的sum、min、max
Indexing, Slicing and Iterating
- 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)
- a[ : :-1] # reversed a,將a進行反轉。a是一維數組。
- 對於多維數組
for row in b: row是每一行。
for element in b.flat: element是每個元素。
Copies and Views
有三種情況:
- No Copy at All,比如b=a,b只是a的引用,不會有新的object被創建,b is a 會返回True
- View or Shallow Copy,比如c = a.view(),c is a返回False,但是c.base is a會返回True,c的值改變,會引起a的值改變,但是c的shape改變,不會引起a的shape改變;
- Deep Copy,比如 d = a.copy(),d is a 與d.base is a 都會返回False,d是一個全新的對象,與a沒有任何關係,d的改變不會引起a的改變。