1. 程式人生 > >Python學習(5):Numpy

Python學習(5):Numpy

1.np屬性事例

>>> import numpy as np
>>> a = np.arange(15).reshape(3,5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> a.shape
(3, 5)
>>> a.ndim
2
>>> a.dtype.name
'int64'
>>> a.dtype
dtype('int64')
>>> a.size
15
>>> a.itemsize
8
>>> type(a)
<class 'numpy.ndarray'>
>>> 
>>> b = np.array([1,2,3,4,5,6,7,8,9])
>>> b
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> c = np.array([1,2,3,4,5,6,'7','a','b'])
>>> c
array(['1', '2', '3', '4', '5', '6', '7', 'a', 'b'], dtype='<U21')
>>> type(b)
<class 'numpy.ndarray'>
>>> type(c)
<class 'numpy.ndarray'>
>>> c.dtype
dtype('<U21')
>>> b.dtype
dtype('int64')
>>> c.itemsize
84
>>> b.itemsize
8

2.建立

numpy.array

它從任何暴露陣列介面的物件,或從返回陣列的任何方法建立一個ndarray。

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)

示例 1

import numpy as np 
a = np.array([1,2,3]) 

示例 2

import numpy as np 
a = np.array([[1,  2],  [3,  4]])

示例 3

# 最小維度  
import numpy as np 
a = np.array([1, 2, 3,4,5], ndmin =  2)  
print a

示例 4

# dtype 引數  
import numpy as np 
a = np.array([1,  2,  3], dtype = complex)  
print a

輸出如下:

[ 1.+0.j,  2.+0.j,  3.+0.j]

注:傳入的引數必須是同一結構,不是同一結構將發生轉換。

>>> import numpy as np
>>> a = np.array([1,2,3.5])
>>> a
array([1. , 2. , 3.5])
>>> b = np.array([1,2,3])
>>> b
array([1, 2, 3])
>>> c = np.array(['1',2,3])
>>> c
array(['1', '2', '3'], dtype='<U1')
>>>

array還可以將序列的序列轉換成二位陣列,可以將序列的序列的序列轉換成三維陣列,以此類推。

>>> import numpy as np
>>> a = np.array([[1,2,3],[2,3,4]])
>>> a
array([[1, 2, 3],
       [2, 3, 4]])
>>> b = np.array([[1,2,3],[2,3,4],[3,4,5]])
>>> b
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5]])
>>>

3.陣列操作
在NumPy中,*用於陣列間元素對應的乘法,而不是矩陣乘法,矩陣乘法可以用dot()方法來實現。

>>> A = np.array([[1,2],[3,4]])
>>> B = np.array([[0,1],[0,1]])
>>> A
array([[1, 2],
       [3, 4]])
>>> B
array([[0, 1],
       [0, 1]])
>>> A*B                    # elementwise product
array([[0, 2],
       [0, 4]])
>>> A.dot(B)               # matrix product
array([[0, 3],
       [0, 7]])
>>> np.dot(A,B)            # another matrix product
array([[0, 3],
       [0, 7]])

當操作不同型別的陣列時,最終的結果陣列的型別取決於精度最寬的陣列的型別。(即所謂的向上造型)

>>> a = np.ones(3, dtype=np.int32)
>>> b = np.linspace(0,pi,3)
>>> b.dtype.name
'float64'
>>> c = a+b
>>> c
array([ 1.        ,  2.57079633,  4.14159265])
>>> c.dtype.name
'float64'
>>> d = np.exp(c*1j)
>>> d
array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,
       -0.54030231-0.84147098j])
>>> d.dtype.name
'complex128'

ndarray類實現了許多運算元組的一元方法,如求和、求最大值、求最小值等。

>>> a = np.random.random((2,3))
>>> a
array([[0.62181697, 0.26165654, 0.34994938],
       [0.95619296, 0.24614291, 0.42120462]])
>>> a.sum()
2.8569633678947346
>>> a.min()
0.24614290611891454
>>> a.max()
0.9561929625193091
>>>

除了上述一元方法以外,NumPy還提供了運算元組中特定行和列的一元方法,通過制定不同的axis來實現。

>>> b = np.arange(12).reshape(3,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> b.sum(axis = 0)                   # sum of each column
array([12, 15, 18, 21])
>>> b.sum(axis = 1)                   # sum of each row
array([ 6, 22, 38])
>>> b.min(axis = 0)                   # min of each column
array([0, 1, 2, 3])
>>> b.min(axis = 1)                   # min of each row
array([0, 4, 8])
>>> b.max(axis = 0)                   # max of each column
array([ 8,  9, 10, 11])
>>> b.max(axis = 1)                   # max of each row
array([ 3,  7, 11])
>>> b.cumsum(axis = 1)                # cumulative sum along each row
array([[ 0,  1,  3,  6],
       [ 4,  9, 15, 22],
       [ 8, 17, 27, 38]])
>>> b.cumsum(axis = 0)                # cumulative sum along each column
array([[ 0,  1,  2,  3],
       [ 4,  6,  8, 10],
       [12, 15, 18, 21]])
>>>

3.陣列索引和迭代
與Python中定義的list一樣,NumPy支援一維陣列的索引、切片和迭代。

a = np.arange(20).reshape(4,5)
print (a)
print
print (a[:,[1,3]])

輸出結果

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]]
 the 2nd and 4th column of a:
[[ 1  3]
 [ 6  8]
 [11 13]
 [16 18]]
>>> a = np.arange(10)**3
>>> a
array([  0,   1,   8,  27,  64, 125, 216, 343, 512, 729])
>>> a[3]
27
>>> a[2:5]
array([ 8, 27, 64])
>>> a[:6:2] = -1111
>>> a
array([-1111,     1, -1111,    27, -1111,   125,   216,   343,   512,
         729])
>>> a[::-1]
array([  729,   512,   343,   216,   125, -1111,    27, -1111,     1,
       -1111])

多維陣列與一維陣列相似,其在每個軸上都有一個對應的索引(index),這些索引是在一個逗號分隔的元組(tuple)中給出的。

>>> b = np.arange(15).reshape(3,5)
>>> b
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])
>>> b[2,3]
13
>>> b[3,3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 3 is out of bounds for axis 0 with size 3
>>> b[0,0]
0
>>> b[0,4]
4
>>> 
>>> 
>>> b[:, 1]
array([ 1,  6, 11])
>>> b[1, :]
array([5, 6, 7, 8, 9])
>>> b[-1]
array([10, 11, 12, 13, 14])
>>> b.shape
(3, 5)

這裡需要注意的是,陣列的第一個索引是從0開始的。一維陣列和多維陣列的迭代,可以參考如下示例:

>>> for row in b:
...     print(row)
...
[0 1 2 3]
[10 11 12 13]
[20 21 22 23]
[30 31 32 33]
[40 41 42 43]

>>> for element in b.flat:
...     print(element)
...
0
1
2
3
10
11
12
13
20
21
22
23
30
31
32
33
40
41
42
43

其中flat屬性是array中的每個元素的迭代器。
4. 陣列堆疊和切片
NumPy支援將多個數據按照不同的軸進行堆疊:

>>> a = np.floor(10*np.random.random((2,2)))
>>> a
array([[0., 8.],
       [4., 8.]])
>>> b = np.floor(10*np.random.random((2,2)))
>>> b
array([[1., 4.],
       [4., 1.]])
>>> np.vstack((a,b))
array([[0., 8.],
       [4., 8.],
       [1., 4.],
       [4., 1.]])
>>> np.hstack((a,b))
array([[0., 8., 1., 4.],
       [4., 8., 4., 1.]])

floor()向下取整,hstack()實現陣列橫向堆疊,vstack()實現陣列縱向堆疊。
5.矩陣運算
Numpy同時提供了矩陣物件(matrix)。矩陣物件和陣列的差別:1)矩陣是二維的,而陣列是任意正整數維的;2)矩陣的*是矩陣乘法,左側矩陣的列和右側的行要想等。陣列可通過asmatrix或mat轉換為矩陣。

a=np.arange(20).reshape(4,5)
a=np.asmatrix(a)

b=np.matrix('1.0 2.0;3.0 4.0')

6.矩陣賦值
b=a矩陣賦值是將b指到a對應資料的記憶體地址上,a的值改變b也跟著變。想要真的複製用copy

b=a.copy()

7.矩陣操作
1.矩陣轉置

#方法1
a=np.transpose(a)
#方法2
b.T

2.矩陣求逆

ia = nlg.inv(a)

3.求特徵值和特徵向量