這篇文章主要介紹Python的numpy庫中的一些函數,做備份,以便查找。
(1)將矩陣轉換為列表的函數:numpy.matrix.tolist()
返回list列表
Examples
>>>
>>> x = np.matrix(np.arange(12).reshape((3,4))); xmatrix([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])>>> x.tolist()[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]
(2)將數組轉換為列表的函數:numpy.ndarray.tolist()
Notes:(數組能夠被重新構造)
The array may be recreated, a=np.array(a.tolist()).
Examples
>>>
>>> a = np.array([1, 2])>>> a.tolist()[1, 2]>>> a = np.array([[1, 2], [3, 4]])>>> list(a)[array([1, 2]), array([3, 4])]>>> a.tolist()[[1, 2], [3, 4]]
(3)numpy.mean()計算矩陣或數組的均值:
Examples
>>>
>>> a = np.array([[1, 2], [3, 4]]) #對所有元素求均值>>> np.mean(a)2.5>>> np.mean(a, axis=0) #對每一列求均值array([ 2., 3.])>>> np.mean(a, axis=1) #對每一行求均值array([ 1.5, 3.5])
(4)numpy.std()計算矩陣或數組的標準差:
Examples
>>>
>>> a = np.array([[1, 2], [3, 4]]) #對所有元素求標準差 >>> np.std(a)1.1180339887498949>>> np.std(a, axis=0) #對每一列求標準差array([ 1., 1.])>>> np.std(a, axis=1) #對每一行求標準差array([ 0.5, 0.5])
(5)numpy.newaxis為數組增加一個維度:
Examples:
>>> a=np.array([[1,2,3],[4,5,6],[7,8,9]]) #先輸入3行2列的數組a>>> b=a[:,:2] >>> b.shape #當數組的行與列都大于1時,不需增加維度(3, 2)>>> c=a[:,2] >>> c.shape #可以看到,當數組只有一列時,缺少列的維度(3,)>>> carray([3, 6, 9])
>>> d=a[:,2,np.newaxis] #np.newaxis實現增加列的維度>>> darray([[3], [6], [9]])>>> d.shape #d的維度成了3行1列(3,1)(3, 1)>>> e=a[:,2,None] #None與np.newaxis實現相同的功能>>> earray([[3], [6], [9]])>>> e.shape(3, 1)
(6)numpy.random.shuffle(index): 打亂數據集(數組)的順序:
Examples:
>>> index = [i for i in range(10)] >>> index [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> np.random.shuffle(index) >>> index [7, 9, 3, 0, 4, 1, 5, 2, 8, 6]
(7)計算二維數組某一行或某一列的最大值最小值:
>>> import numpy as np >>> a = np.arange(15).reshape(5,3) #構造一個5行3列的二維數組 >>> a array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]) >>> b = a[:,0].min() ##取第0列的最小值,其他列同理 >>> b 0 >>> c = a[0,:].max() ##取第0行的最大值,其他行同理 >>> c 2
|
新聞熱點
疑難解答