1. 程式人生 > >Numpy基本操作

Numpy基本操作

基本屬性

  • ndim:維度
  • shape:行數和列數
  • size:元素個數

建立

  • array:陣列
  • dtype:指定資料型別
  • zeros:建立 0 矩陣
  • ones:建立全 1 矩陣
  • empty:建立全接近 0 的矩陣
  • arange:按指定範圍建立資料
  • linspace:建立線段

te

運算

c=a-b  
c=a+b  
c=a*b
c=b**2
c=10*np.sin(a)  
c_dot = np.dot(a,b)#叉積
np.sum(a) 
np.min(a)  
np.max(a)
np.sum(a,axis=1)#0行1列
np.min(a,axis=0)
np.max
(a,axis=1) np.argmin(A)#求最小的索引,矩陣轉化為一行的座標 np.argmax(A) np.mean(A)#平均值 A.mean() A.median()#中位數 np.cumsum(A)#累加 p.diff(A)#每項與後一項的差(後-前) np.nonzero(A)#將所有非零元素的行與列座標分割開,重構成兩個分別關於行和列的矩陣。 np.sort(A)#僅針對每一行進行從小到大排序操作: np.transpose(A)#轉置 A.T np.clip(A,5,9)#將矩陣中元素比最小值小的或者比最大值大的轉換為最小值或者最大值。

索引、合併、分割

A[1
][1] print(A[1, 1:3]) #切片 A.flatten()#將矩陣展開為一行 np.vstack((A,B))#將矩陣上下合併 np.hstack((A,B))#將矩陣左右合併 A[np.newaxis,:]#將array轉化為矩陣,以便用上面兩個函式合併 A[np.newaxis,:] np.concatenate((A,B,B,A),axis=0)#將多個矩陣合併 np.split(A, 3, axis=0)#矩陣橫向平分為3個 np.array_split(A, 3, axis=0)#不均等分割 np.vsplit() np.hsplit()

te

array

a = np.array([2
,23,4]) # list 1d print(a) # [2 23 4] a = np.array([[2,23,4],[2,32,4]]) # 2d 矩陣 2行3列 print(a) """ [[ 2 23 4] [ 2 32 4]] """

dtype

a = np.array([2,23,4],dtype=np.int)
print(a.dtype)
# int64

a = np.array([2,23,4],dtype=np.int32)
print(a.dtype)
# int32
a = np.array([2,23,4],dtype=np.float)
print(a.dtype)
# float64

a = np.array([2,23,4],dtype=np.float32)
print(a.dtype)
# float32

zeros

a = np.zeros((3,4)) # 資料全為0,3行4列
"""
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
"""

empty

a = np.empty((3,4)) # 資料為empty,3行4列
"""
array([[  0.00000000e+000,   4.94065646e-324,   9.88131292e-324,
          1.48219694e-323],
       [  1.97626258e-323,   2.47032823e-323,   2.96439388e-323,
          3.45845952e-323],
       [  3.95252517e-323,   4.44659081e-323,   4.94065646e-323,
          5.43472210e-323]])
"""

arange

a = np.arange(10, 20, 2) # 10-19 的資料,2的步長
"""
array([10, 12, 14, 16, 18])
"""

reshape

a = np.arange(12).reshape((3,4))    # 3行4列,0到11
"""
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
"""

linspace

a = np.linspace(1,10,20)    # 開始端1,結束端10,且分割成20個數據,生成線段
"""
array([  1.        ,   1.47368421,   1.94736842,   2.42105263,
         2.89473684,   3.36842105,   3.84210526,   4.31578947,
         4.78947368,   5.26315789,   5.73684211,   6.21052632,
         6.68421053,   7.15789474,   7.63157895,   8.10526316,
         8.57894737,   9.05263158,   9.52631579,  10.        ])
"""

reshape

a = np.linspace(1,10,20).reshape((5,4)) # 更改shape
"""
array([[  1.        ,   1.47368421,   1.94736842,   2.42105263],
       [  2.89473684,   3.36842105,   3.84210526,   4.31578947],
       [  4.78947368,   5.26315789,   5.73684211,   6.21052632],
       [  6.68421053,   7.15789474,   7.63157895,   8.10526316],
       [  8.57894737,   9.05263158,   9.52631579,  10.        ]])
"""