[Python]Numpy入門教程

一.什麼是Numpy

引自百度百科:Numpy(Numeric Python)系統是Python的一種開源的數值計算擴展。這種工具可用來存儲和處理大型矩陣,比Python自身的嵌套列表結構要高效的多。Numpy提供了許多高級的數值編程工具,如:矩陣數據類型,矢量處理,以及精密的運算庫。

在Python中引入Numpy:

>>> import numpy as np

二.多維數組

1.(1)使用numpy.array方法生成二維數組:

>>> lst = [[1,2,3],[4,5,6]]

>>> nlst = np.array(lst, dtype=np.float16)

(2)numpy.array方法的參數可以為list或者tuple:

tuple:

>>> nlst = np.array(((1,2,3),(4,5,6)))

list:

>>> nlst = np.array([[1,2,3],[4,5,6]])

注意:list或者tuple都可以是任意維的

(3)使用dtype方法指定數組中每個元素的類型:

dtype包括bool, string, int8, int16, int32, int64, uint8, uint16, uint32, uint64, float8, float16, float32, float64, complex(複數)等...

注意:如果沒有指定dtype,numpy.array()方法中的list或者tuple的類型可以為任意的,同一個list或者tuple中的數據類型也可以不同。

如果指定了dtype,numpy.array()方法中的list或者tuple的類型應當與dtype相符。

>>> nlst = np.array([[1,2,3],[4,c,6]])

>>> nlst = np.array([[1,2,3],[4,c,6]], dtype=np.float64)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

ValueError: could not convert string to float: c

第一種方式可以,第二種方式會報錯。

(4)查看數組屬性

使用type方法查看數組類型:

>>> nlst = np.array([[1,2,3],[4,5,6]])

>>> print type(nlst) --->這邊注意哦,如果是2.版本的可以不用小括弧,3.*就必須加小括弧

<type numpy.ndarray>

使用dim查看數組維度:

>>> print nlst.ndim

2

使用shape查看數組每個維度的大小:

>>> print nlst.shape

(2, 3)

使用dtype查看數組中元素的類型:

>>> print nlst.dtype

int64

使用itemsize查看數組中元素的數據類型大小:

int64佔據8個bytes

>>> print nlst.itemsize

8

使用size查看數組中元素的個數:

>>> print nlst.size

6

2.使用numpy.arange()方法生成等差數列

numpy.arange(x,y,z)

其中,x,y指定了等差數列的範圍[x,y)(左閉右開),z指定了數組元素之間的差。x默認為0, z默認為1。np.arange方法至少要指定一個參數y。

>>> nlst = np.arange(11)

>>> print nlst

[ 0 1 2 3 4 5 6 7 8 9 10]

>>> print np.arange(2,12,3)

[ 2 5 8 11]

>>> print np.arange(2,12,5)

[2 7]

>>> print np.arange()

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: Required argument start (pos 1) not found

3.使用numpy.linspace()方法生成等差數列

numpy.linspace(x,y,z)

其中,x,y指定了等差數列的範圍[x,y](左閉右閉),z指定了數組元素的個數,z默認為50個。np.linspace方法至少要指定兩個參數x和y。

>>> print np.linspace(1,3,10)

[ 1. 1.22222222 1.44444444 1.66666667 1.88888889 2.11111111

2.33333333 2.55555556 2.77777778 3. ]

>>> print np.linspace(1,3,5)

[ 1. 1.5 2. 2.5 3. ]

>>> print np.linspace(1,3,3)

[ 1. 2. 3.]

>>> print np.linspace(1,3)

[ 1. 1.04081633 1.08163265 1.12244898 1.16326531 1.20408163

1.24489796 1.28571429 1.32653061 1.36734694 1.40816327 1.44897959

1.48979592 1.53061224 1.57142857 1.6122449 1.65306122 1.69387755

1.73469388 1.7755102 1.81632653 1.85714286 1.89795918 1.93877551

1.97959184 2.02040816 2.06122449 2.10204082 2.14285714 2.18367347

2.2244898 2.26530612 2.30612245 2.34693878 2.3877551 2.42857143

2.46938776 2.51020408 2.55102041 2.59183673 2.63265306 2.67346939

2.71428571 2.75510204 2.79591837 2.83673469 2.87755102 2.91836735

2.95918367 3. ]

>>> print np.linspace(1,2)

[ 1. 1.02040816 1.04081633 1.06122449 1.08163265 1.10204082

1.12244898 1.14285714 1.16326531 1.18367347 1.20408163 1.2244898

1.24489796 1.26530612 1.28571429 1.30612245 1.32653061 1.34693878

1.36734694 1.3877551 1.40816327 1.42857143 1.44897959 1.46938776

1.48979592 1.51020408 1.53061224 1.55102041 1.57142857 1.59183673

1.6122449 1.63265306 1.65306122 1.67346939 1.69387755 1.71428571

1.73469388 1.75510204 1.7755102 1.79591837 1.81632653 1.83673469

1.85714286 1.87755102 1.89795918 1.91836735 1.93877551 1.95918367

1.97959184 2. ]

>>> print np.linspace(1,1)

[ 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.

1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.

1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

>>> print np.linspace(1)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

TypeError: linspace() takes at least 2 arguments (1 given)

三.矩陣

1.使用numpy.zeros方法構造全零矩陣

numpy.zeros方法的參數為矩陣的shape

>>> print np.zeros([2,4])

[[ 0. 0. 0. 0.]

[ 0. 0. 0. 0.]]

2.使用numpy.ones方法構造全一矩陣

numpy.ones方法的參數為矩陣的shape

>>> print np.ones([3,5])

[[ 1. 1. 1. 1. 1.]

[ 1. 1. 1. 1. 1.]

[ 1. 1. 1. 1. 1.]]

3.使用numpy.eye方法構造對角線矩陣

numpy.eye方法的參數為矩陣的大小,只有一個參數

>>> print np.eye(3)

[[ 1. 0. 0.]

[ 0. 1. 0.]

[ 0. 0. 1.]]

4.使用reshape方法構造任意shape的矩陣

>>> print np.arange(1,11).reshape(2,5)

[[ 1 2 3 4 5]

[ 6 7 8 9 10]]

四.隨機數

1. 使用numpy.random.rand方法生成任意隨機數

numpy.random.rand(x,y,z)

表示隨機數的shape為x,y,z...,參數也可以為空,表示只生成一個隨機數

>>> print np.random.rand(2)

[ 0.55750001 0.32018193]

>>> print np.random.rand(2,3)

[[ 0.67643561 0.73340354 0.15798435]

[ 0.9095994 0.42100939 0.68524279]]

>>> print np.random.rand(2,3,4)

[[[ 0.61475145 0.69820104 0.98380555 0.94939185]

[ 0.16583245 0.4105124 0.23284564 0.44771767]

[ 0.58465882 0.43563935 0.0375019 0.18387919]]

[[ 0.20017906 0.23799814 0.68309734 0.03054782]

[ 0.07199248 0.83509683 0.56054471 0.41717739]

[ 0.28308406 0.90862957 0.60933728 0.85992027]]]

>>> print np.random.rand()

0.0501281429998

2.使用np.random.randint方法生成隨機整數

np.random.randint(x,y,z),參數x和參數y指定了隨機數的範圍[x,y)(左閉右開),z指定了生成的隨機數的個數。其中,x默認為0,z默認為1.

np.random.randint方法最少需要指定一個參數y。

>>> print np.random.randint(2)

1

>>> print np.random.randint(2)

0

>>> print np.random.randint(1,5,4)

[1 1 3 3]

>>> print np.random.randint(-1,10,12)

[ 1 9 5 7 -1 -1 -1 9 3 9 7 6]

>>> print np.random.randint()

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "mtrand.pyx", line 905, in mtrand.RandomState.randint (numpy/random/mtrand/mtrand.c:15752)

TypeError: randint() takes at least 1 positional argument (0 given)

3. 使用numpy.random.randn方法生成正態分布的隨機數

numpy.random.randn(x,y,z)

表示隨機數的shape為x,y,z...,參數也可以為空,表示只生成一個隨機數

>>> print np.random.randn() -1.26442307795 >>> print np.random.randn(2,3) [[ 0.82840827 0.45921508 2.59825829] [-1.52275284 1.16471939 -0.08227251]] >>> print np.random.randn(2,3,4) [[[-0.2473765 1.52189224 -0.01250112 -1.54577017] [-0.95470518 -0.9781429 1.28363354 -0.28314614] [ 0.11750765 0.10897544 -0.50437335 0.51158487]]

[[-1.92920176 1.04272466 -0.43805761 -0.22171928]

[-0.60888476 -0.52337761 -0.36497187 -0.2276665 ]

[-0.15758244 -0.77795301 0.12480624 -0.82467094]]]

4.使用np.random.choice方法在指定範圍中選擇數

np.random.choice(x),當x為list或者tuple時,指定了選擇數的範圍為該list或者tuple中包含的數; 當x為>0的整數時,指定了選擇數的範圍為[0,x)

np.random.choice(x,y),y指定隨機數的shape

>>> print np.random.choice(0)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "mtrand.pyx", line 1115, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:17104)

ValueError: a must be greater than 0

>>> print np.random.choice(1.5)

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "mtrand.pyx", line 1113, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:17060)

ValueError: a must be 1-dimensional or an integer

>>> print np.random.choice(2)

1

>>> print np.random.choice((2,3))

3

>>> print np.random.choice([2,3])

2

>>> print np.random.choice(2,3)

[0 1 1]

>>> print np.random.choice(2,4)

[1 0 1 1]

>>> print np.random.choice(2,3,4)

[0 1 0]

>>> print np.random.choice(2,[3,4])

[[1 1 0 1]

[1 0 1 0]

[1 1 0 1]]

>>> print np.random.choice((2,3,5),(2,3))

[[2 5 3]

[5 5 5]]

5.使用numpy.random.uniform方法在均勻分布中隨機採樣

np.random.uniform(x,y,z),參數x和參數y指定了隨機數的範圍[x,y)(左閉右開),z指定了生成的隨機數的個數。其中,x默認為0,y默認為1, z默認為1.

np.random.uniform方法可以不需要參數。

>>> print np.random.uniform(-1,1)

0.0465860330429

>>> print np.random.uniform(-1,1,6)

[-0.42031748 0.54952773 0.06990097 0.48707281 0.21660118 0.51027754]

>>> print np.random.uniform(-1)

0.380192889576

>>> print np.random.uniform()

0.580514461971

五.元素操作

生成2行5列的矩陣

>>> lst = np.arange(10).reshape(2,5)

>>> print lst

[[0 1 2 3 4]

[5 6 7 8 9]]

1.使用numpy.exp方法求exp(矩陣元素)

>>> print np.exp(lst)

[[ 1.00000000e+00 2.71828183e+00 7.38905610e+00 2.00855369e+01

5.45981500e+01]

[ 1.48413159e+02 4.03428793e+02 1.09663316e+03 2.98095799e+03

8.10308393e+03]]

2.使用numpy.exp2方法求pow(2,矩陣元素)

>>> print np.exp2(lst)

[[ 1. 2. 4. 8. 16.]

[ 32. 64. 128. 256. 512.]]

3.使用numpy.sqrt方法求每個矩陣元素的開平方

>>> print np.sqrt(lst)

[[ 0. 1. 1.41421356 1.73205081 2. ]

[ 2.23606798 2.44948974 2.64575131 2.82842712 3. ]]

4.使用numpy.sin方法求每個矩陣元素的三角函數

>>> print np.sin(lst)

[[ 0. 0.84147098 0.90929743 0.14112001 -0.7568025 ]

[-0.95892427 -0.2794155 0.6569866 0.98935825 0.41211849]]

5.使用numpy.log方法求每個矩陣元素的對數

>>> print np.log(lst)

__main__:1: RuntimeWarning: divide by zero encountered in log

[[ -inf 0. 0.69314718 1.09861229 1.38629436]

[ 1.60943791 1.79175947 1.94591015 2.07944154 2.19722458]]

6.使用sum方法計算元素的和

>>> print lst.sum()

45

可以在sum方法中指定axis來計算不同維度的sum值。

>>> print lst.sum(axis=0)

[ 5 7 9 11 13]

>>> print lst.sum(axis=1)

[10 35]

7.使用max和min方法來獲得元素的最大值或者最小值

>>> print lst.max()

9

>>> print lst.min()

0

>>> print lst.max(axis=0)

[5 6 7 8 9]

>>> print lst.max(axis=1)

[4 9]

>>> print lst.min(axis=0)

[0 1 2 3 4]

>>> print lst.min(axis=1)

[0 5]

六.整體間操作

>>> lst1 = np.array([1,2,3,4])

>>> lst2 = np.array([5,6,7,8])

>>> print lst1

[1 2 3 4]

>>> print lst2

[5 6 7 8]

1.相加

>>> print lst1 + lst2

[ 6 8 10 12]

2.相減

>>> print lst1 - lst2

[-4 -4 -4 -4]

3.相乘

>>> print lst1 * lst2

[ 5 12 21 32]

4.相除

>>> print lst1 / lst2

[0 0 0 0]

5.平方

>>> print lst1 ** 2

[ 1 4 9 16]

6.矩陣乘法

>>> print np.dot(lst1.reshape(2,2), lst2.reshape(2,2))

[[19 22]

[43 50]]

7.一個數組追加到另一個數組上

>>> print np.concatenate((lst1,lst2))

[1 2 3 4 5 6 7 8]

>>> print np.concatenate((lst1,lst2), axis=0)

[1 2 3 4 5 6 7 8]

如果是矩陣,可以利用axis實現不同維度上的追加,默認axis=0。

>>> lst3 = np.arange(1,5).reshape(2,2)

>>> lst4 = np.arange(1,5).reshape(2,2)

>>> print lst3,lst4

[[1 2]

[3 4]]

[[1 2]

[3 4]]

>>> print np.concatenate((lst3,lst4), axis=0)

[[1 2]

[3 4]

[1 2]

[3 4]]

>>> print np.concatenate((lst3,lst4), axis=1)

[[1 2 1 2]

[3 4 3 4]]

>>> print np.concatenate((lst3,lst4))

[[1 2]

[3 4]

[1 2]

[3 4]]

或者直接使用numpy.hstack方法和numpy.vstack方法,直接進行水平和垂直方向的追加。

>>> print np.hstack((lst1,lst2))

[1 2 3 4 5 6 7 8]

>>> print np.vstack((lst1,lst2))

[[1 2 3 4]

[5 6 7 8]]

8.數組分割

如將lst1分為兩個數組

>>> print np.split(lst1,2)

[array([1, 2]), array([3, 4])]

9.數組拷貝

>>> print np.copy(lst)

[[0 1 2 3 4]

[5 6 7 8 9]]

注意,copy方法是重新生成了一個對象

>>> lstn = np.copy(lst)

>>> lstn is lst

False

>>> lstm = lst

>>> lstm is lst

True

七.線性代數操作

引入linalg包

>>> from numpy.linalg import *

>>> lst = np.array([1,2,3,4]).reshape(2,2)

>>> print lst

[[1 2]

[3 4]]

1.逆矩陣

>>> print inv(lst)

[[-2. 1. ]

[ 1.5 -0.5]]

2.轉置矩陣

>>> print lst.transpose()

[[1 3]

[2 4]]

3.計算行列式

>>> print det(lst)

-2.0

4.計算特徵值和特徵向量

第一個數組是特徵值,第二個數組是特徵向量

>>> print eig(lst)

(array([-0.37228132, 5.37228132]), array([[-0.82456484, -0.41597356],

[ 0.56576746, -0.90937671]]))

5.求解lst * W = y

>>> y = np.array([5,6,7,8]).reshape(2,2)

>>> print solve(lst,y)

[[-3. -4.]

[ 4. 5.]]

6.求解相關係數

>>> print np.corrcoef([1,0,1],[0,2,1])

[[ 1. -0.8660254]

[-0.8660254 1. ]]


推薦閱讀:

np.pad
python與numpy使用的一些小tips(2)
為什麼用 Numpy 還是慢, 你用對了嗎?
給妹子講python-S02E01初識NumPy
Numpy基本語法示例②

TAG:Python | numpy | 入門教程 |