[TOC]
為什么要用numpy?
Python中提供了list容器,可以當(dāng)作數(shù)組使用。但列表中的元素可以是任何對象,因此列表中保存的是對象的指針,這樣一來,為了保存一個(gè)簡單的列表[1,2,3]。就需要三個(gè)指針和三個(gè)整數(shù)對象。對于數(shù)值運(yùn)算來說,這種結(jié)構(gòu)顯然不夠高效。
Python雖然也提供了array模塊,但其只支持一維數(shù)組,不支持多維數(shù)組(在TensorFlow里面偏向于矩陣?yán)斫?,也沒有各種運(yùn)算函數(shù)。因而不適合數(shù)值運(yùn)算。
NumPy的出現(xiàn)彌補(bǔ)了這些不足。
——摘自張若愚的《Python科學(xué)計(jì)算》
語法:
numpy.array(object, dtype = None, copy = True, order = None, subok = > False, ndmin = 0)
參數(shù)說明:
| 名稱 | 描述 |
|---|---|
| object | 數(shù)組或嵌套的數(shù)列 |
| dtype | 數(shù)組元素的數(shù)據(jù)類型,可選 |
| copy | 對象是否需要復(fù)制,可選 |
| order | 創(chuàng)建數(shù)組的樣式,C為行方向,F(xiàn)為列方向,A為任意方向(默認(rèn)) |
| subok | 默認(rèn)返回一個(gè)與基類類型一致的數(shù)組 |
| ndmin | 指定生成數(shù)組的最小維度 |
實(shí)例:
import numpy as np
## 常規(guī)創(chuàng)建方法
a = np.array([2, 3, 4])
b = np.array([2.0, 3.0, 4.0])
c = np.array([[1.0, 2.0],[3.0, 4.0]])
d = np.array([[1, 2], [3, 4]],dtype=complex) # 指定數(shù)據(jù)類型
print (a, a.dtype)
print (b, b.dtype)
print (c, c.dtype)
print (d, d.dtype)
output:
[2 3 4] int32
[ 2. 3. 4.] float64
[[ 1. 2.]
[ 3. 4.]] float64
[[ 1.+0.j 2.+0.j]
[ 3.+0.j 4.+0.j]] complex128
1、數(shù)組的常用函數(shù):
print np.arange(0,7,1,dtype=np.int16) # 0為起點(diǎn),間隔為1時(shí)可缺省(引起歧義下不可缺省)
print np.ones((2,3,4),dtype=np.int16) # 2頁,3行,4列,全1,指定數(shù)據(jù)類型
print np.zeros((2,3,4)) # 2頁,3行,4列,全0
print np.empty((2,3)) #值取決于內(nèi)存
print np.arange(0,10,2) # 起點(diǎn)為0,不超過10,步長為2
print np.linspace(-1,2,5) # 起點(diǎn)為-1,終點(diǎn)為2,取5個(gè)點(diǎn)
print np.random.randint(0,3,(2,3)) # 大于等于0,小于3,2行3列的隨機(jī)整數(shù)
output:
[0 1 2 3 4 5 6]
[[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]]
[[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]]
[[ 1.39069238e-309 1.39069238e-309 1.39069238e-309]
[ 1.39069238e-309 1.39069238e-309 1.39069238e-309]]
[0 2 4 6 8]
[-1. -0.25 0.5 1.25 2. ]
[[1 0 1]
[0 1 0]]
2、類型轉(zhuǎn)換:
print float(1)
print int(1.0)
print bool(2)
print float(True)
output:
1.0
1
True
1.0
數(shù)組輸出:
從左到右,從上向下;一維數(shù)組打印成行,二維數(shù)組打印成矩陣,三維數(shù)組打印成矩陣列表;
print np.arange(1,6,2)
print np.arange(12).reshape(3,4) # 可以改變輸出形狀
print np.arange(24).reshape(2,3,4)# 2頁,3行,4頁
output:
[1 3 5]
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
3、基本運(yùn)算
## 元素級運(yùn)算
a = np.array([1,2,3,4])
b = np.arange(4)
print (a, b)
print (a-b)
print (a*b)
print (a**2)
print (2*np.sin(a))
print (a>2)
print (np.exp(a)) # 指數(shù)
output:
[1 2 3 4] [0 1 2 3]
[1 1 1 1]
[ 0 2 6 12]
[ 1 4 9 16]
[ 1.68294197 1.81859485 0.28224002 -1.51360499]
[False False True True]
[ 2.71828183 7.3890561 20.08553692 54.59815003]
4、矩陣運(yùn)算(二維數(shù)組)
a = np.array([[1,2],[3,4]]) # 2行2列
b = np.arange(6).reshape((2,-1)) # 2行3列
print (a,b)
print (a.dot(b)) # 2行3列
output:
[[1 2]
[3 4]] [[0 1 2]
[3 4 5]]
[[ 6 9 12]
[12 19 26]]
5、非數(shù)組運(yùn)算,調(diào)用方法
a = np.random.randint(0,5,(2,3))
print (a)
print (a.sum(),a.sum(axis=1),a.sum(0)) # axis用于指定運(yùn)算軸(默認(rèn)全部,可指定0或1)
print (a.min(),a.max(axis=1),a.mean(axis=1)) # axis = 0: 按列計(jì)算,axis = 1: 按行計(jì)算
print (a.cumsum(1)) # 按行計(jì)算累積和
output:
[[2 3 3]
[0 2 1]]
11 [8 3] [2 5 4]
0 [3 2] [ 2.66666667 1. ]
[[2 5 8]
[0 2 3]]
6、索引,切片,迭代
## 一維數(shù)組
a = np.arange(0,10,1)**2
print a
print a[0],a[2],a[-1],a[-2] # 索引從0開始,-1表示最后一個(gè)索引
print a[2:5],a[-5:-1] # 包括起點(diǎn),不包括終點(diǎn)
a[-1] = 100; print a # 賦值
a[1:4]=100; print a # 批量賦值
a[:6:2] = -100; print a # 從開始到第6個(gè)索引,每隔一個(gè)元素(步長=2)賦值
print a[: :-1];print a # 將a逆序輸出,a本身未發(fā)生改變
b = [np.sqrt(np.abs(i)) for i in a]; print b # 通過遍歷賦值
output:
[ 0 1 4 9 16 25 36 49 64 81]
0 4 81 64
[ 4 9 16] [25 36 49 64]
[ 0 1 4 9 16 25 36 49 64 100]
[ 0 100 100 100 16 25 36 49 64 100]
[-100 100 -100 100 -100 25 36 49 64 100]
[ 100 64 49 36 25 -100 100 -100 100 -100]
[-100 100 -100 100 -100 25 36 49 64 100]
[10.0, 10.0, 10.0, 10.0, 10.0, 5.0, 6.0, 7.0, 8.0, 10.0]
7、多維數(shù)組
a = np.arange(0,20).reshape((4,5))
print (a, a[2,3], a[:,1], a[1:4,2], a[1:3,:])
print (a[-1]) # 相當(dāng)于a[-1,:],即索引少于軸數(shù)時(shí),確實(shí)的索引默認(rèn)為整個(gè)切片
b = np.arange(0,24).reshape((2,3,4))
print (b,b[1]) # 相當(dāng)于b[1,:,:] 和b[1,...]
print '-------------------'
for row in a:
print (row) # 遍歷以第一個(gè)軸為基礎(chǔ)
output:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]] 13 [ 1 6 11 16] [ 7 12 17] [[ 5 6 7 8 9]
[10 11 12 13 14]]
[15 16 17 18 19]
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]
-------------------
[0 1 2 3 4]
[5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
8、形狀操作
a = np.floor(10*np.random.random((3,4)))
print a, a.shape #輸出a的形狀
print a.ravel() # 輸出平坦化后的a(a本身不改變)
a.shape = (6,2); print a # 改變a的形狀
print a.transpose() # 輸出a的轉(zhuǎn)置
output:
[[ 0. 4. 3. 2.]
[ 1. 1. 3. 3.]
[ 4. 4. 6. 5.]] (3, 4)
[ 0. 4. 3. 2. 1. 1. 3. 3. 4. 4. 6. 5.]
[[ 0. 4.]
[ 3. 2.]
[ 1. 1.]
[ 3. 3.]
[ 4. 4.]
[ 6. 5.]]
[[ 0. 3. 1. 3. 4. 6.]
[ 4. 2. 1. 3. 4. 5.]]
補(bǔ)充:reshape和resize
a = np.array([[1,2,3],[4,5,6]])
b = a
a.reshape((3,2))# 不改變數(shù)組本身的形狀
print a
b.resize((3,2))# 改變數(shù)組本身形狀
print b
output:
[[1 2 3]
[4 5 6]]
[[1 2]
[3 4]
[5 6]]
在numpy模塊中,我們經(jīng)常會(huì)使用resize 和 reshape,在具體使用中,通常是使用resize改變數(shù)組的尺寸大小,使用reshape用來增加數(shù)組的維度。
1.resize
之前看到別人的博客說,resize沒有返回值,其實(shí)這取決于你如何使用resize,resize有兩種使用方式,一種是沒有返回值的,直接對原始的數(shù)據(jù)進(jìn)行修改,還有一種用法是有返回值的,所以不會(huì)修改原有的數(shù)組值。
1.1 有返回值,不對原始數(shù)據(jù)進(jìn)行修改
import numpy as np
X=np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
X_new=np.resize(X,(3,3)) # do not change the original X
print("X:\n",X) #original X
print("X_new:\n",X_new) # new X
---------------------
>>
X:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]
X_new:
[[1 2 3]
[4 5 6]
[7 8 9]]
1.2 無返回值,直接修改原始數(shù)組的大小
import numpy as np
X=np.array([[1,2,3,4],
[5,6,7,8],
[9,10,11,12]])
X_2=X.resize((3,3)) #change the original X ,and do not return a value
print("X:\n",X) # change the original X
print("X_2:\n",X_2) # return None
-------------------
>>
X:
[[1 2 3]
[4 5 6]
[7 8 9]]
X_2:
None
2.reshape
給數(shù)組一個(gè)新的形狀而不改變其數(shù)據(jù)
import numpy as np
X=np.array([1,2,3,4,5,6,7,8])
X_2=X.reshape((2,4)) #retuen a 2*4 2-dim array
X_3=X.reshape((2,2,2)) # retuen a 2*2*2 3-dim array
print("X:\n",X)
print("X_2:\n",X_2)
print("X_3:\n",X_3)
---------------------
>>
X:
[1 2 3 4 5 6 7 8]
X_2:
[[1 2 3 4]
[5 6 7 8]]
X_3:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
參考文獻(xiàn):
【墨曉白】https://blog.csdn.net/qq_24193303/article/details/80965274
【菜鳥教程】https://www.runoob.com/numpy/numpy-tutorial.html
【fanfan4569】https://blog.csdn.net/fanfan4569/article/details/85256266