
一、NumPy簡(jiǎn)介
NumPy系統(tǒng)是Python的一種開源的數(shù)值計(jì)算擴(kuò)展。這種工具可用來存儲(chǔ)和處理大型矩陣,比Python自身的嵌套列表(nested list structure)結(jié)構(gòu)要高效的多(該結(jié)構(gòu)也可以用來表示矩陣(matrix))。
以下為官方英文介紹:
NumPy is the fundamental package for scientific computing with Python. It contains among other things:
(1)a powerful N-dimensional array object
(2)sophisticated (broadcasting) functions
(3)tools for integrating C/C++ and Fortran code
(4)useful linear algebra, Fourier transform, and random number capabilities
Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.
二、python環(huán)境注意事項(xiàng)
目前python3使用也比較多,有的同學(xué)可能安裝了兩個(gè)版本,包括python2,Mac 在終端中輸入python命令后,輸出的信息還是Python 2.7。
如何讓系統(tǒng)默認(rèn)使用python3呢?按照以下步驟設(shè)置即可:
(1) 終端輸入:open ~/.bash_profile,打開.bash_profile文件。
(2)修改.bash_profile文件內(nèi)容 ,添加如下兩行PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH(3)添加別名 alias python=``"/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6"
(4)重新生效.bash_profile文件
source .bash_profile
經(jīng)過以上四步,終端輸入phtyon,出現(xiàn)以下內(nèi)容即修改成功。

三、NumPy安裝
配置好python環(huán)境后,在命令行輸入:from numpy import*,如果提示以下錯(cuò)誤,我們需要手動(dòng)安裝NumPy:

(1)pip安裝
我們使用pip安裝NumPy,前提是已經(jīng)安裝pip,mac默認(rèn)是沒有安裝pip的。
如果用的是macOS自帶的python2.7,直接終端輸入:sudo easy_install pip,安裝。
如果使用的Python3,終端輸入:curl https://bootstrap.pypa.io/get-pip.py | python3。
安裝完成后,查看pip的版本和路徑。由于我分別安裝了python2和3,所以也分別安裝了pip的不同版本,如下:


注意:
1)使用pip install XXX
新安裝的庫(kù)會(huì)放在這個(gè)目錄下面
python2.7/site-packages
2)使用pip3 install XXX
新安裝的庫(kù)會(huì)放在這個(gè)目錄下面
python3.6/site-packages
在使用python3執(zhí)行程序,那么就不能import python2.7/site-packages中的庫(kù)。
(2)安裝NumPy
終端輸入:sudo pip3 install -U numpy
安裝成功輸出以下log:

四、NumPy使用
(1)基礎(chǔ)
NumPy的主要對(duì)象是同類型的多維數(shù)組。它是一張表,所有元素(通常是數(shù)字)的類型都相同,并通過正整數(shù)元組索引。在NumPy中,維度稱為軸。軸的數(shù)目為rank。
例如,3D空間中的點(diǎn)的坐標(biāo)[1, 2, 1]是rank為1的數(shù)組,因?yàn)樗哂幸粋€(gè)軸。該軸的長(zhǎng)度為3。在下圖所示的示例中,數(shù)組的rank為2(它是2維的)。第一維度(軸)的長(zhǎng)度為2,第二維度的長(zhǎng)度為3。
[[ 1., 0., 0.],
[ 0., 1., 2.]]
NumPy的數(shù)組的類稱為ndarray。別名為array。請(qǐng)注意,numpy.array與標(biāo)準(zhǔn)Python庫(kù)的類array.array不同,后者僅處理一維數(shù)組并提供較少的功能。ndarray對(duì)象的更重要的屬性是:
ndarray.ndim
數(shù)組的軸(維度)的個(gè)數(shù)。在Python世界中,維度的數(shù)量被稱為rank。
ndarray.shape
數(shù)組的維度。這是一個(gè)整數(shù)的元組,表示每個(gè)維度中數(shù)組的大小。對(duì)于具有n行和m列的矩陣,shape將是(n,m)。因此,shape元組的長(zhǎng)度就是rank或維度的個(gè)數(shù)ndim。
ndarray.size
數(shù)組元素的總數(shù)。這等于shape的元素的乘積。
ndarray.dtype
描述數(shù)組中元素類型的對(duì)象。可以使用標(biāo)準(zhǔn)Python類型創(chuàng)建或指定dtype。另外NumPy提供了自己的類型。例如numpy.int32、numpy.int16和numpy.float64。
ndarray.itemsize
數(shù)組中每個(gè)元素的字節(jié)大小。例如,元素為float64類型的數(shù)組的itemsize為8(=64/8),而complex32類型的數(shù)組的comitemsize為4(=32/8)。它等于ndarray.dtype.itemsize。
ndarray.data
該緩沖區(qū)包含數(shù)組的實(shí)際元素。通常,我們不需要使用此屬性,因?yàn)槲覀儗⑹褂盟饕L問數(shù)組中的元素。
舉例說明:
import numpy as np
#這里我們生成了一個(gè)一維數(shù)組a,從0開始,步長(zhǎng)為1,長(zhǎng)度為20
a = np.arange(15)
print('a:',a)
#打印a的類型,應(yīng)該是array
print('a type:',type(a))
#通過函數(shù)"reshape",我們可以重新構(gòu)造一下這個(gè)數(shù)組,例如,我們可以構(gòu)造一個(gè)3*5的二維數(shù)組
a = a.reshape(3, 5)
print('a.reshape:',a)
#數(shù)組的維度
print('a.shape:',a.shape)
#數(shù)組的維度的個(gè)數(shù)
print('a.ndim:',a.ndim)
#數(shù)組元素總數(shù)
print('a.size:',a.size)
#數(shù)組元素類型
print('a.dtype:',a.dtype)
#數(shù)組元素的字節(jié)大小
print('a.itemsize:',a.itemsize)
對(duì)應(yīng)輸出如下:
a: [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
a type: <class 'numpy.ndarray'>
a.reshape: [[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
a.shape: (3, 5)
a.ndim: 2
a.size: 15
a.dtype: int64
a.itemsize: 8
(2)數(shù)組創(chuàng)建
有幾種方法來創(chuàng)建數(shù)組,可以使用array函數(shù)從常規(guī)Python列表或元組中創(chuàng)建數(shù)組。得到的數(shù)組的類型從序列中元素的類型推導(dǎo)出。
>>> a = array( [2,3,4] )
>>> a
array([2, 3, 4])
>>> a.dtype
dtype('int32')
>>> b = array([1.2, 3.5, 5.1])
>>> b.dtype
dtype('float64') 一個(gè)常見的錯(cuò)誤包括用多個(gè)數(shù)值參數(shù)調(diào)用`array`而不是提供一個(gè)由數(shù)值組成的列表作為一個(gè)參數(shù)。
>>> a = array(1,2,3,4) # WRONG
>>> a = array([1,2,3,4]) # RIGHT
(3)數(shù)組打印
當(dāng)你打印一個(gè)數(shù)組,NumPy以類似嵌套列表的形式顯示它,但是呈以下布局:
最后的軸從左到右打印
次后的軸從頂向下打印
剩下的軸從頂向下打印,每個(gè)切片通過一個(gè)空行與下一個(gè)隔開
一維數(shù)組被打印成行,二維數(shù)組成矩陣,三維數(shù)組成矩陣列表。
>>> a = arange(6) # 1d array
>>> print a
[0 1 2 3 4 5]
>>>
>>> b = arange(12).reshape(4,3) # 2d array
>>> print b
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
>>>
>>> c = arange(24).reshape(2,3,4) # 3d array
>>> print c
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
(4)數(shù)組運(yùn)算
數(shù)組上的算術(shù)運(yùn)算符使用元素級(jí)別。將創(chuàng)建一個(gè)新數(shù)組并用結(jié)果填充。
>>> a = np.array( [20,30,40,50] )
>>> b = np.arange( 4 )
>>> b
array([0, 1, 2, 3])
>>> c = a-b
>>> c
array([20, 29, 38, 47])
>>> b**2
array([0, 1, 4, 9])
>>> 10*np.sin(a)
array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854])
>>> a<35
array([ True, True, False, False], dtype=bool)
與許多矩陣語言不同,乘法運(yùn)算符*的運(yùn)算在NumPy數(shù)組中是元素級(jí)別的??梢允褂胐ot函數(shù)或方法執(zhí)行矩陣乘積:
>>> A = np.array( [[1,1],
... [0,1]] )
>>> B = np.array( [[2,0],
... [3,4]] )
>>> A*B # elementwise product
array([[2, 0],
[0, 4]])
>>> A.dot(B) # matrix product
array([[5, 4],
[3, 4]])
>>> np.dot(A, B) # another matrix product
array([[5, 4],
[3, 4]])
某些操作(如+=和*=)可以修改現(xiàn)有數(shù)組,而不是創(chuàng)建新數(shù)組。
>>> a = np.ones((2,3), dtype=int)
>>> b = np.random.random((2,3))
>>> a *= 3
>>> a
array([[3, 3, 3],
[3, 3, 3]])
>>> b += a
>>> b
array([[ 3.417022 , 3.72032449, 3.00011437],
[ 3.30233257, 3.14675589, 3.09233859]])
>>> a += b # b is not automatically converted to integer type
Traceback (most recent call last):
...
TypeError: Cannot cast ufunc add output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
此外,NumPy還有很多強(qiáng)大的功能,大家如果有需要可以到官方參考文檔。