NumPy - 簡介
NumPy 是一個 Python 包。 它代表 “Numeric Python”。 它是一個由多維數組對象和用於處理數組的例程集合組成的庫。
Numeric,即 NumPy 的前身,是由 Jim Hugunin 開發的。 也開發了另一個包 Numarray ,它擁有一些額外的功能。 2005年,Travis Oliphant 通過將 Numarray 的功能集成到 Numeric 包中來創建 NumPy 包。 這個開源項目有很多貢獻者。
NumPy 操作
使用NumPy,開發人員可以執行以下操作:
-
數組的算數和邏輯運算。
-
傅立葉變換和用於圖形操作的例程。
-
與線性代數有關的操作。 NumPy 擁有線性代數和隨機數生成的內置函數。
NumPy – MatLab 的替代之一
NumPy 通常與 SciPy(Scientific Python)和 Matplotlib(繪圖庫)一起使用。 這種組合廣泛用於替代 MatLab,是一個流行的技術計算平台。 但是,Python 作為 MatLab 的替代方案,現在被視為一種更加現代和完整的編程語言。
NumPy 是開源的,這是它的一個額外的優勢。
NumPy - Ndarray 對象
NumPy 中定義的最重要的對象是稱為 ndarray 的 N 維數組類型。 它描述相同類型的元素集合。 可以使用基於零的索引訪問集合中的項目。
ndarray中的每個元素在內存中使用相同大小的塊。 ndarray中的每個元素是數據類型對象的對象(稱為 dtype)。
從ndarray對象提取的任何元素(通過切片)由一個數組標量類型的 Python 對象表示。 下圖顯示了ndarray,數據類型對象(dtype)和數組標量類型之間的關系。
ndarray類的實例可以通過本教程后面描述的不同的數組創建例程來構造。 基本的ndarray是使用 NumPy 中的數組函數創建的,如下所示:
numpy.array
它從任何暴露數組接口的對象,或從返回數組的任何方法創建一個ndarray。
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
上面的構造器接受以下參數:
| 序號 | 參數及描述 |
|---|---|
| 1. | object 任何暴露數組接口方法的對象都會返回一個數組或任何(嵌套)序列。 |
| 2. | dtype 數組的所需數據類型,可選。 |
| 3. | copy 可選,默認為true,對象是否被復制。 |
| 4. | order C(按行)、F(按列)或A(任意,默認)。 |
| 5. | subok 默認情況下,返回的數組被強制為基類數組。 如果為true,則返回子類。 |
| 6. | ndimin 指定返回數組的最小維數。 |
看看下面的例子來更好地理解。
示例 1
import numpy as np a = np.array([1,2,3]) print a
輸出如下:
[1, 2, 3]
示例 2
# 多於一個維度 import numpy as np a = np.array([[1, 2], [3, 4]]) print a
輸出如下:
[[1, 2]
[3, 4]]
示例 3
# 最小維度 import numpy as np a = np.array([1, 2, 3,4,5], ndmin = 2) print a
輸出如下:
[[1, 2, 3, 4, 5]]
示例 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]
**ndarray ** 對象由計算機內存中的一維連續區域組成,帶有將每個元素映射到內存塊中某個位置的索引方案。 內存塊以按行(C 風格)或按列(FORTRAN 或 MatLab 風格)的方式保存元素。
NumPy - 數據類型
NumPy 支持比 Python 更多種類的數值類型。 下表顯示了 NumPy 中定義的不同標量數據類型。
| 序號 | 數據類型及描述 |
|---|---|
| 1. | bool_ 存儲為一個字節的布爾值(真或假) |
| 2. | int_ 默認整數,相當於 C 的long,通常為int32或int64 |
| 3. | intc 相當於 C 的int,通常為int32或int64 |
| 4. | intp 用於索引的整數,相當於 C 的size_t,通常為int32或int64 |
| 5. | int8 字節(-128 ~ 127) |
| 6. | int16 16 位整數(-32768 ~ 32767) |
| 7. | int32 32 位整數(-2147483648 ~ 2147483647) |
| 8. | int64 64 位整數(-9223372036854775808 ~ 9223372036854775807) |
| 9. | uint8 8 位無符號整數(0 ~ 255) |
| 10. | uint16 16 位無符號整數(0 ~ 65535) |
| 11. | uint32 32 位無符號整數(0 ~ 4294967295) |
| 12. | uint64 64 位無符號整數(0 ~ 18446744073709551615) |
| 13. | float_ float64的簡寫 |
| 14. | float16 半精度浮點:符號位,5 位指數,10 位尾數 |
| 15. | float32 單精度浮點:符號位,8 位指數,23 位尾數 |
| 16. | float64 雙精度浮點:符號位,11 位指數,52 位尾數 |
| 17. | complex_ complex128的簡寫 |
| 18. | complex64 復數,由兩個 32 位浮點表示(實部和虛部) |
| 19. | complex128 復數,由兩個 64 位浮點表示(實部和虛部) |
NumPy 數字類型是dtype(數據類型)對象的實例,每個對象具有唯一的特征。 這些類型可以是np.bool_,np.float32等。
數據類型對象 (dtype)
數據類型對象描述了對應於數組的固定內存塊的解釋,取決於以下方面:
-
數據類型(整數、浮點或者 Python 對象)
-
數據大小
-
字節序(小端或大端)
-
在結構化類型的情況下,字段的名稱,每個字段的數據類型,和每個字段占用的內存塊部分。
-
如果數據類型是子序列,它的形狀和數據類型。
字節順序取決於數據類型的前綴<或>。 <意味着編碼是小端(最小有效字節存儲在最小地址中)。 >意味着編碼是大端(最大有效字節存儲在最小地址中)。
dtype可由一下語法構造:
numpy.dtype(object, align, copy)
參數為:
-
Object:被轉換為數據類型的對象。 -
Align:如果為true,則向字段添加間隔,使其類似 C 的結構體。 -
Copy? 生成dtype對象的新副本,如果為flase,結果是內建數據類型對象的引用。
示例 1
# 使用數組標量類型 import numpy as np dt = np.dtype(np.int32) print dt
輸出如下:
int32
示例 2
#int8,int16,int32,int64 可替換為等價的字符串 'i1','i2','i4',以及其他。 import numpy as np dt = np.dtype('i4') print dt
輸出如下:
int32
示例 3
# 使用端記號 import numpy as np dt = np.dtype('>i4') print dt
輸出如下:
>i4
下面的例子展示了結構化數據類型的使用。 這里聲明了字段名稱和相應的標量數據類型。
示例 4
# 首先創建結構化數據類型。 import numpy as np dt = np.dtype([('age',np.int8)]) print dt
輸出如下:
[('age', 'i1')]
示例 5
# 現在將其應用於 ndarray 對象 import numpy as np dt = np.dtype([('age',np.int8)]) a = np.array([(10,),(20,),(30,)], dtype = dt) print a
輸出如下:
[(10,) (20,) (30,)]
示例 6
# 文件名稱可用於訪問 age 列的內容 import numpy as np dt = np.dtype([('age',np.int8)]) a = np.array([(10,),(20,),(30,)], dtype = dt) print a['age']
輸出如下:
[10 20 30]
示例 7
以下示例定義名為 student 的結構化數據類型,其中包含字符串字段name,整數字段age和浮點字段marks。 此dtype應用於ndarray對象。
import numpy as np student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) print student
輸出如下:
[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])
示例 8
import numpy as np student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student) print a
輸出如下:
[('abc', 21, 50.0), ('xyz', 18, 75.0)]
每個內建類型都有一個唯一定義它的字符代碼:
-
'b':布爾值 -
'i':符號整數 -
'u':無符號整數 -
'f':浮點 -
'c':復數浮點 -
'm':時間間隔 -
'M':日期時間 -
'O':Python 對象 -
'S', 'a':字節串 -
'U':Unicode -
'V':原始數據(void)
NumPy - 數組屬性
這一章中,我們會討論 NumPy 的多種數組屬性。
ndarray.shape
這一數組屬性返回一個包含數組維度的元組,它也可以用於調整數組大小。
示例 1
import numpy as np a = np.array([[1,2,3],[4,5,6]]) print a.shape
輸出如下:
(2, 3)
示例 2
# 這會調整數組大小 import numpy as np a = np.array([[1,2,3],[4,5,6]]) a.shape = (3,2) print a
輸出如下:
[[1, 2]
[3, 4]
[5, 6]]
示例 3
NumPy 也提供了reshape函數來調整數組大小。
import numpy as np a = np.array([[1,2,3],[4,5,6]]) b = a.reshape(3,2) print b
輸出如下:
[[1, 2]
[3, 4]
[5, 6]]
ndarray.ndim
這一數組屬性返回數組的維數。
示例 1
# 等間隔數字的數組 import numpy as np a = np.arange(24) print a
輸出如下:
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
示例 2
# 一維數組 import numpy as np a = np.arange(24) a.ndim # 現在調整其大小 b = a.reshape(2,4,3) print b # b 現在擁有三個維度
輸出如下:
[[[ 0, 1, 2]
[ 3, 4, 5]
[ 6, 7, 8]
[ 9, 10, 11]]
[[12, 13, 14]
[15, 16, 17]
[18, 19, 20]
[21, 22, 23]]]
numpy.itemsize
這一數組屬性返回數組中每個元素的字節單位長度。
示例 1
# 數組的 dtype 為 int8(一個字節) import numpy as np x = np.array([1,2,3,4,5], dtype = np.int8) print x.itemsize
輸出如下:
1
示例 2
# 數組的 dtype 現在為 float32(四個字節) import numpy as np x = np.array([1,2,3,4,5], dtype = np.float32) print x.itemsize
輸出如下:
4
numpy.flags
ndarray對象擁有以下屬性。這個函數返回了它們的當前值。
| 序號 | 屬性及描述 |
|---|---|
| 1. | C_CONTIGUOUS (C) 數組位於單一的、C 風格的連續區段內 |
| 2. | F_CONTIGUOUS (F) 數組位於單一的、Fortran 風格的連續區段內 |
| 3. | OWNDATA (O) 數組的內存從其它對象處借用 |
| 4. | WRITEABLE (W) 數據區域可寫入。 將它設置為flase會鎖定數據,使其只讀 |
| 5. | ALIGNED (A) 數據和任何元素會為硬件適當對齊 |
| 6. | UPDATEIFCOPY (U) 這個數組是另一數組的副本。當這個數組釋放時,源數組會由這個數組中的元素更新 |
示例
下面的例子展示當前的標志。
import numpy as np x = np.array([1,2,3,4,5]) print x.flags
輸出如下:
C_CONTIGUOUS : True F_CONTIGUOUS : True OWNDATA : True WRITEABLE : True ALIGNED : True UPDATEIFCOPY : False
NumPy - 數組創建例程
新的ndarray對象可以通過任何下列數組創建例程或使用低級ndarray構造函數構造。
numpy.empty
它創建指定形狀和dtype的未初始化數組。 它使用以下構造函數:
numpy.empty(shape, dtype = float, order = 'C')
構造器接受下列參數:
| 序號 | 參數及描述 |
|---|---|
| 1. | Shape 空數組的形狀,整數或整數元組 |
| 2. | Dtype 所需的輸出數組類型,可選 |
| 3. | Order 'C'為按行的 C 風格數組,'F'為按列的 Fortran 風格數組 |
示例
下面的代碼展示空數組的例子:
import numpy as np x = np.empty([3,2], dtype = int) print x
輸出如下:
[[22649312 1701344351]
[1818321759 1885959276]
[16779776 156368896]]
注意:數組元素為隨機值,因為它們未初始化。
numpy.zeros
返回特定大小,以 0 填充的新數組。
numpy.zeros(shape, dtype = float, order = 'C')
構造器接受下列參數:
| 序號 | 參數及描述 |
|---|---|
| 1. | Shape 空數組的形狀,整數或整數元組 |
| 2. | Dtype 所需的輸出數組類型,可選 |
| 3. | Order 'C'為按行的 C 風格數組,'F'為按列的 Fortran 風格數組 |
示例 1
# 含有 5 個 0 的數組,默認類型為 float import numpy as np x = np.zeros(5) print x
輸出如下:
[ 0. 0. 0. 0. 0.]
示例 2
import numpy as np x = np.zeros((5,), dtype = np.int) print x
輸出如下:
[0 0 0 0 0]
示例 3
# 自定義類型 import numpy as np x = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')]) print x
輸出如下:
[[(0,0)(0,0)]
[(0,0)(0,0)]]
numpy.ones
返回特定大小,以 1 填充的新數組。
numpy.ones(shape, dtype = None, order = 'C')
構造器接受下列參數:
| 序號 | 參數及描述 |
|---|---|
| 1. | Shape 空數組的形狀,整數或整數元組 |
| 2. | Dtype 所需的輸出數組類型,可選 |
| 3. | Order 'C'為按行的 C 風格數組,'F'為按列的 Fortran 風格數組 |
示例 1
# 含有 5 個 1 的數組,默認類型為 float import numpy as np x = np.ones(5) print x
輸出如下:
[ 1. 1. 1. 1. 1.]
示例 2
import numpy as np x = np.ones([2,2], dtype = int) print x
輸出如下:
[[1 1]
[1 1]]
NumPy - 來自現有數據的數組
這一章中,我們會討論如何從現有數據創建數組。
numpy.asarray
此函數類似於numpy.array,除了它有較少的參數。 這個例程對於將 Python 序列轉換為ndarray非常有用。
numpy.asarray(a, dtype = None, order = None)
構造器接受下列參數:
| 序號 | 參數及描述 |
|---|---|
| 1. | a 任意形式的輸入參數,比如列表、列表的元組、元組、元組的元組、元組的列表 |
| 2. | dtype 通常,輸入數據的類型會應用到返回的ndarray |
| 3. | order 'C'為按行的 C 風格數組,'F'為按列的 Fortran 風格數組 |
下面的例子展示了如何使用asarray函數:
示例 1
# 將列表轉換為 ndarray import numpy as np x = [1,2,3] a = np.asarray(x) print a
輸出如下:
[1 2 3]
示例 2
# 設置了 dtype import numpy as np x = [1,2,3] a = np.asarray(x, dtype = float) print a
輸出如下:
[ 1. 2. 3.]
示例 3
# 來自元組的 ndarray import numpy as np x = (1,2,3) a = np.asarray(x) print a
輸出如下:
[1 2 3]
示例 4
# 來自元組列表的 ndarray import numpy as np x = [(1,2,3),(4,5)] a = np.asarray(x) print a
輸出如下:
[(1, 2, 3) (4, 5)]
numpy.frombuffer
此函數將緩沖區解釋為一維數組。 暴露緩沖區接口的任何對象都用作參數來返回ndarray。
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
構造器接受下列參數:
| 序號 | 參數及描述 |
|---|---|
| 1. | buffer 任何暴露緩沖區借口的對象 |
| 2. | dtype 返回數組的數據類型,默認為float |
| 3. | count 需要讀取的數據數量,默認為-1,讀取所有數據 |
| 4. | offset 需要讀取的起始位置,默認為0 |
示例
下面的例子展示了frombuffer函數的用法。
import numpy as np s = 'Hello World' a = np.frombuffer(s, dtype = 'S1') print a
輸出如下:
['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
numpy.fromiter
此函數從任何可迭代對象構建一個ndarray對象,返回一個新的一維數組。
numpy.fromiter(iterable, dtype, count = -1)
構造器接受下列參數:
| 序號 | 參數及描述 |
|---|---|
| 1. | iterable 任何可迭代對象 |
| 2. | dtype 返回數組的數據類型 |
| 3. | count 需要讀取的數據數量,默認為-1,讀取所有數據 |
以下示例展示了如何使用內置的range()函數返回列表對象。 此列表的迭代器用於形成ndarray對象。
示例 1
# 使用 range 函數創建列表對象 import numpy as np list = range(5) print list
輸出如下:
[0, 1, 2, 3, 4]
示例 2
# 從列表中獲得迭代器 import numpy as np list = range(5) it = iter(list) # 使用迭代器創建 ndarray x = np.fromiter(it, dtype = float) print x
輸出如下:
[0. 1. 2. 3. 4.]
NumPy - 來自數值范圍的數組
這一章中,我們會學到如何從數值范圍創建數組。
numpy.arange
這個函數返回ndarray對象,包含給定范圍內的等間隔值。
numpy.arange(start, stop, step, dtype)
構造器接受下列參數:
| 序號 | 參數及描述 |
|---|---|
| 1. | start 范圍的起始值,默認為0 |
| 2. | stop 范圍的終止值(不包含) |
| 3. | step 兩個值的間隔,默認為1 |
| 4. | dtype 返回ndarray的數據類型,如果沒有提供,則會使用輸入數據的類型。 |
下面的例子展示了如何使用該函數:
示例 1
import numpy as np x = np.arange(5) print x
輸出如下:
[0 1 2 3 4]
示例 2
import numpy as np # 設置了 dtype x = np.arange(5, dtype = float) print x
輸出如下:
[0. 1. 2. 3. 4.]
示例 3
# 設置了起始值和終止值參數 import numpy as np x = np.arange(10,20,2) print x
輸出如下:
[10 12 14 16 18]
numpy.linspace
此函數類似於arange()函數。 在此函數中,指定了范圍之間的均勻間隔數量,而不是步長。 此函數的用法如下。
numpy.linspace(start, stop, num, endpoint, retstep, dtype)
構造器接受下列參數:
| 序號 | 參數及描述 |
|---|---|
| 1. | start 序列的起始值 |
| 2. | stop 序列的終止值,如果endpoint為true,該值包含於序列中 |
| 3. | num 要生成的等間隔樣例數量,默認為50 |
| 4. | endpoint 序列中是否包含stop值,默認為ture |
| 5. | retstep 如果為true,返回樣例,以及連續數字之間的步長 |
| 6. | dtype 輸出ndarray的數據類型 |
下面的例子展示了linspace函數的用法。
示例 1
import numpy as np x = np.linspace(10,20,5) print x
輸出如下:
[10. 12.5 15. 17.5 20.]
示例 2
# 將 endpoint 設為 false import numpy as np x = np.linspace(10,20, 5, endpoint = False) print x
輸出如下:
[10. 12. 14. 16. 18.]
示例 3
# 輸出 retstep 值 import numpy as np x = np.linspace(1,2,5, retstep = True) print x # 這里的 retstep 為 0.25
輸出如下:
(array([ 1. , 1.25, 1.5 , 1.75, 2. ]), 0.25)
numpy.logspace
此函數返回一個ndarray對象,其中包含在對數刻度上均勻分布的數字。 刻度的開始和結束端點是某個底數的冪,通常為 10。
numpy.logscale(start, stop, num, endpoint, base, dtype)
logspace函數的輸出由以下參數決定:
| 序號 | 參數及描述 |
|---|---|
| 1. | start 起始值是base ** start |
| 2. | stop 終止值是base ** stop |
| 3. | num 范圍內的數值數量,默認為50 |
| 4. | endpoint 如果為true,終止值包含在輸出數組當中 |
| 5. | base 對數空間的底數,默認為10 |
| 6. | dtype 輸出數組的數據類型,如果沒有提供,則取決於其它參數 |
下面的例子展示了logspace函數的用法。
示例 1
import numpy as np # 默認底數是 10 a = np.logspace(1.0, 2.0, num = 10) print a
輸出如下:
[ 10. 12.91549665 16.68100537 21.5443469 27.82559402
35.93813664 46.41588834 59.94842503 77.42636827 100. ]
示例 2
# 將對數空間的底數設置為 2 import numpy as np a = np.logspace(1,10,num = 10, base = 2) print a
輸出如下:
[ 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.]
NumPy - 切片和索引
ndarray對象的內容可以通過索引或切片來訪問和修改,就像 Python 的內置容器對象一樣。
如前所述,ndarray對象中的元素遵循基於零的索引。 有三種可用的索引方法類型: 字段訪問,基本切片和高級索引。
基本切片是 Python 中基本切片概念到 n 維的擴展。 通過將start,stop和step參數提供給內置的slice函數來構造一個 Python slice對象。 此slice對象被傳遞給數組來提取數組的一部分。
示例 1
import numpy as np a = np.arange(10) s = slice(2,7,2) print a[s]
輸出如下:
[2 4 6]
在上面的例子中,ndarray對象由arange()函數創建。 然后,分別用起始,終止和步長值2,7和2定義切片對象。 當這個切片對象傳遞給ndarray時,會對它的一部分進行切片,從索引2到7,步長為2。
通過將由冒號分隔的切片參數(start:stop:step)直接提供給ndarray對象,也可以獲得相同的結果。
示例 2
import numpy as np a = np.arange(10) b = a[2:7:2] print b
輸出如下:
[2 4 6]
如果只輸入一個參數,則將返回與索引對應的單個項目。 如果使用a:,則從該索引向后的所有項目將被提取。 如果使用兩個參數(以:分隔),則對兩個索引(不包括停止索引)之間的元素以默認步驟進行切片。
示例 3
# 對單個元素進行切片 import numpy as np a = np.arange(10) b = a[5] print b
輸出如下:
5
示例 4
# 對始於索引的元素進行切片 import numpy as np a = np.arange(10) print a[2:]
輸出如下:
[2 3 4 5 6 7 8 9]
示例 5
# 對索引之間的元素進行切片 import numpy as np a = np.arange(10) print a[2:5]
輸出如下:
[2 3 4]
上面的描述也可用於多維ndarray。
示例 6
import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print a # 對始於索引的元素進行切片 print '現在我們從索引 a[1:] 開始對數組切片' print a[1:]
輸出如下:
[[1 2 3] [3 4 5] [4 5 6]] 現在我們從索引 a[1:] 開始對數組切片 [[3 4 5] [4 5 6]]
切片還可以包括省略號(...),來使選擇元組的長度與數組的維度相同。 如果在行位置使用省略號,它將返回包含行中元素的ndarray。
示例 7
# 最開始的數組 import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print '我們的數組是:' print a print '\n' # 這會返回第二列元素的數組: print '第二列的元素是:' print a[...,1] print '\n' # 現在我們從第二行切片所有元素: print '第二行的元素是:' print a[1,...] print '\n' # 現在我們從第二列向后切片所有元素: print '第二列及其剩余元素是:' print a[...,1:]
輸出如下:
我們的數組是: [[1 2 3] [3 4 5] [4 5 6]] 第二列的元素是: [2 4 5] 第二行的元素是: [3 4 5] 第二列及其剩余元素是: [[2 3] [4 5] [5 6]]
NumPy - 高級索引
如果一個ndarray是非元組序列,數據類型為整數或布爾值的ndarray,或者至少一個元素為序列對象的元組,我們就能夠用它來索引ndarray。高級索引始終返回數據的副本。 與此相反,切片只提供了一個視圖。
有兩種類型的高級索引:整數和布爾值。
整數索引
這種機制有助於基於 N 維索引來獲取數組中任意元素。 每個整數數組表示該維度的下標值。 當索引的元素個數就是目標ndarray的維度時,會變得相當直接。
以下示例獲取了ndarray對象中每一行指定列的一個元素。 因此,行索引包含所有行號,列索引指定要選擇的元素。
示例 1
import numpy as np x = np.array([[1, 2], [3, 4], [5, 6]]) y = x[[0,1,2], [0,1,0]] print y
輸出如下:
[1 4 5]
該結果包括數組中(0,0),(1,1)和(2,0)位置處的元素。
下面的示例獲取了 4X3 數組中的每個角處的元素。 行索引是[0,0]和[3,3],而列索引是[0,2]和[0,2]。
示例 2
import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print '我們的數組是:' print x print '\n' rows = np.array([[0,0],[3,3]]) cols = np.array([[0,2],[0,2]]) y = x[rows,cols] print '這個數組的每個角處的元素是:' print y
輸出如下:
我們的數組是: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] 這個數組的每個角處的元素是: [[ 0 2] [ 9 11]]
返回的結果是包含每個角元素的ndarray對象。
高級和基本索引可以通過使用切片:或省略號...與索引數組組合。 以下示例使用slice作為列索引和高級索引。 當切片用於兩者時,結果是相同的。 但高級索引會導致復制,並且可能有不同的內存布局。
示例 3
import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print '我們的數組是:' print x print '\n' # 切片 z = x[1:4,1:3] print '切片之后,我們的數組變為:' print z print '\n' # 對列使用高級索引 y = x[1:4,[1,2]] print '對列使用高級索引來切片:' print y
輸出如下:
我們的數組是: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] 切片之后,我們的數組變為: [[ 4 5] [ 7 8] [10 11]] 對列使用高級索引來切片: [[ 4 5] [ 7 8] [10 11]]
布爾索引
當結果對象是布爾運算(例如比較運算符)的結果時,將使用此類型的高級索引。
示例 1
這個例子中,大於 5 的元素會作為布爾索引的結果返回。
import numpy as np x = np.array([[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8],[ 9, 10, 11]]) print '我們的數組是:' print x print '\n' # 現在我們會打印出大於 5 的元素 print '大於 5 的元素是:' print x[x > 5]
輸出如下:
我們的數組是: [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] 大於 5 的元素是: [ 6 7 8 9 10 11]
示例 2
這個例子使用了~(取補運算符)來過濾NaN。
import numpy as np a = np.array([np.nan, 1,2,np.nan,3,4,5]) print a[~np.isnan(a)]
輸出如下:
[ 1. 2. 3. 4. 5.]
示例 3
以下示例顯示如何從數組中過濾掉非復數元素。
import numpy as np a = np.array([1, 2+6j, 5, 3.5+5j]) print a[np.iscomplex(a)]
輸出如下:
[2.0+6.j 3.5+5.j]
NumPy - 廣播
術語廣播是指 NumPy 在算術運算期間處理不同形狀的數組的能力。 對數組的算術運算通常在相應的元素上進行。 如果兩個陣列具有完全相同的形狀,則這些操作被無縫執行。
示例 1
import numpy as np a = np.array([1,2,3,4]) b = np.array([10,20,30,40]) c = a * b print c
輸出如下:
[10 40 90 160]
如果兩個數組的維數不相同,則元素到元素的操作是不可能的。 然而,在 NumPy 中仍然可以對形狀不相似的數組進行操作,因為它擁有廣播功能。 較小的數組會廣播到較大數組的大小,以便使它們的形狀可兼容。
如果滿足以下規則,可以進行廣播:
-
ndim較小的數組會在前面追加一個長度為 1 的維度。 -
輸出數組的每個維度的大小是輸入數組該維度大小的最大值。
-
如果輸入在每個維度中的大小與輸出大小匹配,或其值正好為 1,則在計算中可它。
-
如果輸入的某個維度大小為 1,則該維度中的第一個數據元素將用於該維度的所有計算。
如果上述規則產生有效結果,並且滿足以下條件之一,那么數組被稱為可廣播的。
-
數組擁有相同形狀。
-
數組擁有相同的維數,每個維度擁有相同長度,或者長度為 1。
-
數組擁有極少的維度,可以在其前面追加長度為 1 的維度,使上述條件成立。
下面的例稱展示了廣播的示例。
示例 2
import numpy as np a = np.array([[0.0,0.0,0.0],[10.0,10.0,10.0],[20.0,20.0,20.0],[30.0,30.0,30.0]]) b = np.array([1.0,2.0,3.0]) print '第一個數組:' print a print '\n' print '第二個數組:' print b print '\n' print '第一個數組加第二個數組:' print a + b
輸出如下:
第一個數組: [[ 0. 0. 0.] [ 10. 10. 10.] [ 20. 20. 20.] [ 30. 30. 30.]] 第二個數組: [ 1. 2. 3.] 第一個數組加第二個數組: [[ 1. 2. 3.] [ 11. 12. 13.] [ 21. 22. 23.] [ 31. 32. 33.]]
下面的圖片展示了數組b如何通過廣播來與數組a兼容。
NumPy - 數組上的迭代
NumPy 包包含一個迭代器對象numpy.nditer。 它是一個有效的多維迭代器對象,可以用於在數組上進行迭代。 數組的每個元素可使用 Python 的標准Iterator接口來訪問。
讓我們使用arange()函數創建一個 3X4 數組,並使用nditer對它進行迭代。
示例 1
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print '原始數組是:' print a print '\n' print '修改后的數組是:' for x in np.nditer(a): print x,
輸出如下:
原始數組是: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] 修改后的數組是: 0 5 10 15 20 25 30 35 40 45 50 55
示例 2
迭代的順序匹配數組的內容布局,而不考慮特定的排序。 這可以通過迭代上述數組的轉置來看到。
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print '原始數組是:' print a print '\n' print '原始數組的轉置是:' b = a.T print b print '\n' print '修改后的數組是:' for x in np.nditer(b): print x,
輸出如下:
原始數組是: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] 原始數組的轉置是: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] 修改后的數組是: 0 5 10 15 20 25 30 35 40 45 50 55
迭代順序
如果相同元素使用 F 風格順序存儲,則迭代器選擇以更有效的方式對數組進行迭代。
示例 1
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print '原始數組是:' print a print '\n' print '原始數組的轉置是:' b = a.T print b print '\n' print '以 C 風格順序排序:' c = b.copy(order='C') print c for x in np.nditer(c): print x, print '\n' print '以 F 風格順序排序:' c = b.copy(order='F') print c for x in np.nditer(c): print x,
輸出如下:
原始數組是: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] 原始數組的轉置是: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] 以 C 風格順序排序: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] 0 20 40 5 25 45 10 30 50 15 35 55 以 F 風格順序排序: [[ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]] 0 5 10 15 20 25 30 35 40 45 50 55
示例 2
可以通過顯式提醒,來強制nditer對象使用某種順序:
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print '原始數組是:' print a print '\n' print '以 C 風格順序排序:' for x in np.nditer(a, order = 'C'): print x, print '\n' print '以 F 風格順序排序:' for x in np.nditer(a, order = 'F'): print x,
輸出如下:
原始數組是: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] 以 C 風格順序排序: 0 5 10 15 20 25 30 35 40 45 50 55 以 F 風格順序排序: 0 20 40 5 25 45 10 30 50 15 35 55
修改數組的值
nditer對象有另一個可選參數op_flags。 其默認值為只讀,但可以設置為讀寫或只寫模式。 這將允許使用此迭代器修改數組元素。
示例
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print '原始數組是:' print a print '\n' for x in np.nditer(a, op_flags=['readwrite']): x[...]=2*x print '修改后的數組是:' print a
輸出如下:
原始數組是: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] 修改后的數組是: [[ 0 10 20 30] [ 40 50 60 70] [ 80 90 100 110]]
外部循環
nditer類的構造器擁有flags參數,它可以接受下列值:
| 序號 | 參數及描述 |
|---|---|
| 1. | c_index 可以跟蹤 C 順序的索引 |
| 2. | f_index 可以跟蹤 Fortran 順序的索引 |
| 3. | multi-index 每次迭代可以跟蹤一種索引類型 |
| 4. | external_loop 給出的值是具有多個值的一維數組,而不是零維數組 |
示例
在下面的示例中,迭代器遍歷對應於每列的一維數組。
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print '原始數組是:' print a print '\n' print '修改后的數組是:' for x in np.nditer(a, flags = ['external_loop'], order = 'F'): print x,
輸出如下:
原始數組是: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] 修改后的數組是: [ 0 20 40] [ 5 25 45] [10 30 50] [15 35 55]
廣播迭代
如果兩個數組是可廣播的,nditer組合對象能夠同時迭代它們。 假設數組a具有維度 3X4,並且存在維度為 1X4 的另一個數組b,則使用以下類型的迭代器(數組b被廣播到a的大小)。
示例
import numpy as np a = np.arange(0,60,5) a = a.reshape(3,4) print '第一個數組:' print a print '\n' print '第二個數組:' b = np.array([1, 2, 3, 4], dtype = int) print b print '\n' print '修改后的數組是:' for x,y in np.nditer([a,b]): print "%d:%d" % (x,y),
輸出如下:
第一個數組: [[ 0 5 10 15] [20 25 30 35] [40 45 50 55]] 第二個數組: [1 2 3 4] 修改后的數組是: 0:1 5:2 10:3 15:4 20:1 25:2 30:3 35:4 40:1 45:2 50:3 55:4
NumPy - 數組操作
NumPy包中有幾個例程用於處理ndarray對象中的元素。 它們可以分為以下類型:
修改形狀
| 序號 | 形狀及描述 |
|---|---|
| 1. | reshape 不改變數據的條件下修改形狀 |
| 2. | flat 數組上的一維迭代器 |
| 3. | flatten 返回折疊為一維的數組副本 |
| 4. | ravel 返回連續的展開數組 |
numpy.reshape
這個函數在不改變數據的條件下修改形狀,它接受如下參數:
numpy.reshape(arr, newshape, order')
其中:
arr:要修改形狀的數組newshape:整數或者整數數組,新的形狀應當兼容原有形狀order:'C'為 C 風格順序,'F'為 F 風格順序,'A'為保留原順序。
例子
import numpy as np a = np.arange(8) print '原始數組:' print a print '\n' b = a.reshape(4,2) print '修改后的數組:' print b
輸出如下:
原始數組: [0 1 2 3 4 5 6 7] 修改后的數組: [[0 1] [2 3] [4 5] [6 7]]
numpy.ndarray.flat
該函數返回數組上的一維迭代器,行為類似 Python 內建的迭代器。
例子
import numpy as np a = np.arange(8).reshape(2,4) print '原始數組:' print a print '\n' print '調用 flat 函數之后:' # 返回展開數組中的下標的對應元素 print a.flat[5]
輸出如下:
原始數組: [[0 1 2 3] [4 5 6 7]] 調用 flat 函數之后: 5
numpy.ndarray.flatten
該函數返回折疊為一維的數組副本,函數接受下列參數:
ndarray.flatten(order)
其中:
order:'C'-- 按行,'F'-- 按列,'A'-- 原順序,'k'-- 元素在內存中的出現順序。
例子
import numpy as np a = np.arange(8).reshape(2,4) print '原數組:' print a print '\n' # default is column-major print '展開的數組:' print a.flatten() print '\n' print '以 F 風格順序展開的數組:' print a.flatten(order = 'F')
輸出如下:
原數組: [[0 1 2 3] [4 5 6 7]] 展開的數組: [0 1 2 3 4 5 6 7] 以 F 風格順序展開的數組: [0 4 1 5 2 6 3 7]
numpy.ravel
這個函數返回展開的一維數組,並且按需生成副本。返回的數組和輸入數組擁有相同數據類型。這個函數接受兩個參數。
numpy.ravel(a, order)
構造器接受下列參數:
order:'C'-- 按行,'F'-- 按列,'A'-- 原順序,'k'-- 元素在內存中的出現順序。
例子
import numpy as np a = np.arange(8).reshape(2,4) print '原數組:' print a print '\n' print '調用 ravel 函數之后:' print a.ravel() print '\n' print '以 F 風格順序調用 ravel 函數之后:' print a.ravel(order = 'F')
原數組: [[0 1 2 3] [4 5 6 7]] 調用 ravel 函數之后: [0 1 2 3 4 5 6 7] 以 F 風格順序調用 ravel 函數之后: [0 4 1 5 2 6 3 7]
翻轉操作
| 序號 | 操作及描述 |
|---|---|
| 1. | transpose 翻轉數組的維度 |
| 2. | ndarray.T 和self.transpose()相同 |
| 3. | rollaxis 向后滾動指定的軸 |
| 4. | swapaxes 互換數組的兩個軸 |
numpy.transpose
這個函數翻轉給定數組的維度。如果可能的話它會返回一個視圖。函數接受下列參數:
numpy.transpose(arr, axes)
其中:
arr:要轉置的數組axes:整數的列表,對應維度,通常所有維度都會翻轉。
例子
import numpy as np a = np.arange(12).reshape(3,4) print '原數組:' print a print '\n' print '轉置數組:' print np.transpose(a)
輸出如下:
原數組: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 轉置數組: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
numpy.ndarray.T
該函數屬於ndarray類,行為類似於numpy.transpose。
例子
import numpy as np a = np.arange(12).reshape(3,4) print '原數組:' print a print '\n' print '轉置數組:' print a.T
輸出如下:
原數組: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 轉置數組: [[ 0 4 8] [ 1 5 9] [ 2 6 10] [ 3 7 11]]
numpy.rollaxis
該函數向后滾動特定的軸,直到一個特定位置。這個函數接受三個參數:
numpy.rollaxis(arr, axis, start)
其中:
arr:輸入數組axis:要向后滾動的軸,其它軸的相對位置不會改變start:默認為零,表示完整的滾動。會滾動到特定位置。
例子
# 創建了三維的 ndarray import numpy as np a = np.arange(8).reshape(2,2,2) print '原數組:' print a print '\n' # 將軸 2 滾動到軸 0(寬度到深度) print '調用 rollaxis 函數:' print np.rollaxis(a,2) # 將軸 0 滾動到軸 1:(寬度到高度) print '\n' print '調用 rollaxis 函數:' print np.rollaxis(a,2,1)
輸出如下:
原數組: [[[0 1] [2 3]] [[4 5] [6 7]]] 調用 rollaxis 函數: [[[0 2] [4 6]] [[1 3] [5 7]]] 調用 rollaxis 函數: [[[0 2] [1 3]] [[4 6] [5 7]]]
numpy.swapaxes
該函數交換數組的兩個軸。對於 1.10 之前的 NumPy 版本,會返回交換后數組的試圖。這個函數接受下列參數:
numpy.swapaxes(arr, axis1, axis2)
arr:要交換其軸的輸入數組axis1:對應第一個軸的整數axis2:對應第二個軸的整數
# 創建了三維的 ndarray import numpy as np a = np.arange(8).reshape(2,2,2) print '原數組:' print a print '\n' # 現在交換軸 0(深度方向)到軸 2(寬度方向) print '調用 swapaxes 函數后的數組:' print np.swapaxes(a, 2, 0)
輸出如下:
原數組: [[[0 1] [2 3]] [[4 5] [6 7]]] 調用 swapaxes 函數后的數組: [[[0 4] [2 6]] [[1 5] [3 7]]]
修改維度
| 序號 | 維度和描述 |
|---|---|
| 1. | broadcast 產生模仿廣播的對象 |
| 2. | broadcast_to 將數組廣播到新形狀 |
| 3. | expand_dims 擴展數組的形狀 |
| 4. | squeeze 從數組的形狀中刪除單維條目 |
broadcast
如前所述,NumPy 已經內置了對廣播的支持。 此功能模仿廣播機制。 它返回一個對象,該對象封裝了將一個數組廣播到另一個數組的結果。
該函數使用兩個數組作為輸入參數。 下面的例子說明了它的用法。
import numpy as np x = np.array([[1], [2], [3]]) y = np.array([4, 5, 6]) # 對 y 廣播 x b = np.broadcast(x,y) # 它擁有 iterator 屬性,基於自身組件的迭代器元組 print '對 y 廣播 x:' r,c = b.iters print r.next(), c.next() print r.next(), c.next() print '\n' # shape 屬性返回廣播對象的形狀 print '廣播對象的形狀:' print b.shape print '\n' # 手動使用 broadcast 將 x 與 y 相加 b = np.broadcast(x,y) c = np.empty(b.shape) print '手動使用 broadcast 將 x 與 y 相加:' print c.shape print '\n' c.flat = [u + v for (u,v) in b] print '調用 flat 函數:' print c print '\n' # 獲得了和 NumPy 內建的廣播支持相同的結果 print 'x 與 y 的和:' print x + y
輸出如下:
對 y 廣播 x: 1 4 1 5 廣播對象的形狀: (3, 3) 手動使用 broadcast 將 x 與 y 相加: (3, 3) 調用 flat 函數: [[ 5. 6. 7.] [ 6. 7. 8.] [ 7. 8. 9.]] x 與 y 的和: [[5 6 7] [6 7 8] [7 8 9]]
numpy.broadcast_to
此函數將數組廣播到新形狀。 它在原始數組上返回只讀視圖。 它通常不連續。 如果新形狀不符合 NumPy 的廣播規則,該函數可能會拋出ValueError。
注意 - 此功能可用於 1.10.0 及以后的版本。
該函數接受以下參數。
numpy.broadcast_to(array, shape, subok)
例子
import numpy as np a = np.arange(4).reshape(1,4) print '原數組:' print a print '\n' print '調用 broadcast_to 函數之后:' print np.broadcast_to(a,(4,4))
輸出如下:
[[0 1 2 3]
[0 1 2 3]
[0 1 2 3]
[0 1 2 3]]
numpy.expand_dims
函數通過在指定位置插入新的軸來擴展數組形狀。該函數需要兩個參數:
numpy.expand_dims(arr, axis)
其中:
arr:輸入數組axis:新軸插入的位置
例子
import numpy as np x = np.array(([1,2],[3,4])) print '數組 x:' print x print '\n' y = np.expand_dims(x, axis = 0) print '數組 y:' print y print '\n' print '數組 x 和 y 的形狀:' print x.shape, y.shape print '\n' # 在位置 1 插入軸 y = np.expand_dims(x, axis = 1) print '在位置 1 插入軸之后的數組 y:' print y print '\n' print 'x.ndim 和 y.ndim:' print x.ndim,y.ndim print '\n' print 'x.shape 和 y.shape:' print x.shape, y.shape
輸出如下:
數組 x: [[1 2] [3 4]] 數組 y: [[[1 2] [3 4]]] 數組 x 和 y 的形狀: (2, 2) (1, 2, 2) 在位置 1 插入軸之后的數組 y: [[[1 2]] [[3 4]]] x.shape 和 y.shape: 2 3 x.shape and y.shape: (2, 2) (2, 1, 2)
numpy.squeeze
函數從給定數組的形狀中刪除一維條目。 此函數需要兩個參數。
numpy.squeeze(arr, axis)
其中:
arr:輸入數組axis:整數或整數元組,用於選擇形狀中單一維度條目的子集
例子
import numpy as np x = np.arange(9).reshape(1,3,3) print '數組 x:' print x print '\n' y = np.squeeze(x) print '數組 y:' print y print '\n' print '數組 x 和 y 的形狀:' print x.shape, y.shape
輸出如下:
數組 x: [[[0 1 2] [3 4 5] [6 7 8]]] 數組 y: [[0 1 2] [3 4 5] [6 7 8]] 數組 x 和 y 的形狀: (1, 3, 3) (3, 3)
數組的連接
| 序號 | 數組及描述 |
|---|---|
| 1. | concatenate 沿着現存的軸連接數據序列 |
| 2. | stack 沿着新軸連接數組序列 |
| 3. | hstack 水平堆疊序列中的數組(列方向) |
| 4. | vstack 豎直堆疊序列中的數組(行方向) |
numpy.concatenate
數組的連接是指連接。 此函數用於沿指定軸連接相同形狀的兩個或多個數組。 該函數接受以下參數。
numpy.concatenate((a1, a2, ...), axis)
其中:
a1, a2, ...:相同類型的數組序列axis:沿着它連接數組的軸,默認為 0
例子
import numpy as np a = np.array([[1,2],[3,4]]) print '第一個數組:' print a print '\n' b = np.array([[5,6],[7,8]]) print '第二個數組:' print b print '\n' # 兩個數組的維度相同 print '沿軸 0 連接兩個數組:' print np.concatenate((a,b)) print '\n' print '沿軸 1 連接兩個數組:' print np.concatenate((a,b),axis = 1)
輸出如下:
第一個數組: [[1 2] [3 4]] 第二個數組: [[5 6] [7 8]] 沿軸 0 連接兩個數組: [[1 2] [3 4] [5 6] [7 8]] 沿軸 1 連接兩個數組: [[1 2 5 6] [3 4 7 8]]
numpy.stack
此函數沿新軸連接數組序列。 此功能添加自 NumPy 版本 1.10.0。 需要提供以下參數。
numpy.stack(arrays, axis)
其中:
arrays:相同形狀的數組序列axis:返回數組中的軸,輸入數組沿着它來堆疊
import numpy as np a = np.array([[1,2],[3,4]]) print '第一個數組:' print a print '\n' b = np.array([[5,6],[7,8]]) print '第二個數組:' print b print '\n' print '沿軸 0 堆疊兩個數組:' print np.stack((a,b),0) print '\n' print '沿軸 1 堆疊兩個數組:' print np.stack((a,b),1)
輸出如下:
第一個數組: [[1 2] [3 4]] 第二個數組: [[5 6] [7 8]] 沿軸 0 堆疊兩個數組: [[[1 2] [3 4]] [[5 6] [7 8]]] 沿軸 1 堆疊兩個數組: [[[1 2] [5 6]] [[3 4] [7 8]]]
numpy.hstack
numpy.stack函數的變體,通過堆疊來生成水平的單個數組。
例子
import numpy as np a = np.array([[1,2],[3,4]]) print '第一個數組:' print a print '\n' b = np.array([[5,6],[7,8]]) print '第二個數組:' print b print '\n' print '水平堆疊:' c = np.hstack((a,b)) print c print '\n'
輸出如下:
第一個數組: [[1 2] [3 4]] 第二個數組: [[5 6] [7 8]] 水平堆疊: [[1 2 5 6] [3 4 7 8]]
numpy.vstack
numpy.stack函數的變體,通過堆疊來生成豎直的單個數組。
import numpy as np a = np.array([[1,2],[3,4]]) print '第一個數組:' print a print '\n' b = np.array([[5,6],[7,8]]) print '第二個數組:' print b print '\n' print '豎直堆疊:' c = np.vstack((a,b)) print c
輸出如下:
第一個數組: [[1 2] [3 4]] 第二個數組: [[5 6] [7 8]] 豎直堆疊: [[1 2] [3 4] [5 6] [7 8]]
數組分割
| 序號 | 數組及操作 |
|---|---|
| 1. | split 將一個數組分割為多個子數組 |
| 2. | hsplit 將一個數組水平分割為多個子數組(按列) |
| 3. | vsplit 將一個數組豎直分割為多個子數組(按行) |
numpy.split
該函數沿特定的軸將數組分割為子數組。函數接受三個參數:
numpy.split(ary, indices_or_sections, axis)
其中:
ary:被分割的輸入數組indices_or_sections:可以是整數,表明要從輸入數組創建的,等大小的子數組的數量。 如果此參數是一維數組,則其元素表明要創建新子數組的點。axis:默認為 0
例子
import numpy as np a = np.arange(9) print '第一個數組:' print a print '\n' print '將數組分為三個大小相等的子數組:' b = np.split(a,3) print b print '\n' print '將數組在一維數組中表明的位置分割:' b = np.split(a,[4,7]) print b
輸出如下:
第一個數組: [0 1 2 3 4 5 6 7 8] 將數組分為三個大小相等的子數組: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])] 將數組在一維數組中表明的位置分割: [array([0, 1, 2, 3]), array([4, 5, 6]), array([7, 8])]
numpy.hsplit
numpy.hsplit是split()函數的特例,其中軸為 1 表示水平分割,無論輸入數組的維度是什么。
import numpy as np a = np.arange(16).reshape(4,4) print '第一個數組:' print a print '\n' print '水平分割:' b = np.hsplit(a,2) print b print '\n'
輸出:
第一個數組: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] 水平分割: [array([[ 0, 1], [ 4, 5], [ 8, 9], [12, 13]]), array([[ 2, 3], [ 6, 7], [10, 11], [14, 15]])]
numpy.vsplit
numpy.vsplit是split()函數的特例,其中軸為 0 表示豎直分割,無論輸入數組的維度是什么。下面的例子使之更清楚。
import numpy as np a = np.arange(16).reshape(4,4) print '第一個數組:' print a print '\n' print '豎直分割:' b = np.vsplit(a,2) print b
輸出如下:
第一個數組: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] 豎直分割: [array([[0, 1, 2, 3], [4, 5, 6, 7]]), array([[ 8, 9, 10, 11], [12, 13, 14, 15]])]
添加/刪除元素
| 序號 | 元素及描述 |
|---|---|
| 1. | resize 返回指定形狀的新數組 |
| 2. | append 將值添加到數組末尾 |
| 3. | insert 沿指定軸將值插入到指定下標之前 |
| 4. | delete 返回刪掉某個軸的子數組的新數組 |
| 5. | unique 尋找數組內的唯一元素 |
numpy.resize
此函數返回指定大小的新數組。 如果新大小大於原始大小,則包含原始數組中的元素的重復副本。 該函數接受以下參數。
numpy.resize(arr, shape)
其中:
arr:要修改大小的輸入數組shape:返回數組的新形狀
例子
import numpy as np a = np.array([[1,2,3],[4,5,6]]) print '第一個數組:' print a print '\n' print '第一個數組的形狀:' print a.shape print '\n' b = np.resize(a, (3,2)) print '第二個數組:' print b print '\n' print '第二個數組的形狀:' print b.shape print '\n' # 要注意 a 的第一行在 b 中重復出現,因為尺寸變大了 print '修改第二個數組的大小:' b = np.resize(a,(3,3)) print b
輸出如下:
第一個數組: [[1 2 3] [4 5 6]] 第一個數組的形狀: (2, 3) 第二個數組: [[1 2] [3 4] [5 6]] 第二個數組的形狀: (3, 2) 修改第二個數組的大小: [[1 2 3] [4 5 6] [1 2 3]]
numpy.append
此函數在輸入數組的末尾添加值。 附加操作不是原地的,而是分配新的數組。 此外,輸入數組的維度必須匹配否則將生成ValueError。
函數接受下列函數:
numpy.append(arr, values, axis)
其中:
arr:輸入數組values:要向arr添加的值,比如和arr形狀相同(除了要添加的軸)axis:沿着它完成操作的軸。如果沒有提供,兩個參數都會被展開。
例子
import numpy as np a = np.array([[1,2,3],[4,5,6]]) print '第一個數組:' print a print '\n' print '向數組添加元素:' print np.append(a, [7,8,9]) print '\n' print '沿軸 0 添加元素:' print np.append(a, [[7,8,9]],axis = 0) print '\n' print '沿軸 1 添加元素:' print np.append(a, [[5,5,5],[7,8,9]],axis = 1)
輸出如下:
第一個數組: [[1 2 3] [4 5 6]] 向數組添加元素: [1 2 3 4 5 6 7 8 9] 沿軸 0 添加元素: [[1 2 3] [4 5 6] [7 8 9]] 沿軸 1 添加元素: [[1 2 3 5 5 5] [4 5 6 7 8 9]]
numpy.insert
此函數在給定索引之前,沿給定軸在輸入數組中插入值。 如果值的類型轉換為要插入,則它與輸入數組不同。 插入沒有原地的,函數會返回一個新數組。 此外,如果未提供軸,則輸入數組會被展開。
insert()函數接受以下參數:
numpy.insert(arr, obj, values, axis)
其中:
arr:輸入數組obj:在其之前插入值的索引values:要插入的值axis:沿着它插入的軸,如果未提供,則輸入數組會被展開
例子
import numpy as np a = np.array([[1,2],[3,4],[5,6]]) print '第一個數組:' print a print '\n' print '未傳遞 Axis 參數。 在插入之前輸入數組會被展開。' print np.insert(a,3,[11,12]) print '\n' print '傳遞了 Axis 參數。 會廣播值數組來配輸入數組。' print '沿軸 0 廣播:' print np.insert(a,1,[11],axis = 0) print '\n' print '沿軸 1 廣播:' print np.insert(a,1,11,axis = 1)
numpy.delete
此函數返回從輸入數組中刪除指定子數組的新數組。 與insert()函數的情況一樣,如果未提供軸參數,則輸入數組將展開。 該函數接受以下參數:
Numpy.delete(arr, obj, axis)
其中:
arr:輸入數組obj:可以被切片,整數或者整數數組,表明要從輸入數組刪除的子數組axis:沿着它刪除給定子數組的軸,如果未提供,則輸入數組會被展開
例子
import numpy as np a = np.arange(12).reshape(3,4) print '第一個數組:' print a print '\n' print '未傳遞 Axis 參數。 在插入之前輸入數組會被展開。' print np.delete(a,5) print '\n' print '刪除第二列:' print np.delete(a,1,axis = 1) print '\n' print '包含從數組中刪除的替代值的切片:' a = np.array([1,2,3,4,5,6,7,8,9,10]) print np.delete(a, np.s_[::2])
輸出如下:
第一個數組: [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] 未傳遞 Axis 參數。 在插入之前輸入數組會被展開。 [ 0 1 2 3 4 6 7 8 9 10 11] 刪除第二列: [[ 0 2 3] [ 4 6 7] [ 8 10 11]] 包含從數組中刪除的替代值的切片: [ 2 4 6 8 10]
numpy.unique
此函數返回輸入數組中的去重元素數組。 該函數能夠返回一個元組,包含去重數組和相關索引的數組。 索引的性質取決於函數調用中返回參數的類型。
numpy.unique(arr, return_index, return_inverse, return_counts)
其中:
arr:輸入數組,如果不是一維數組則會展開return_index:如果為true,返回輸入數組中的元素下標return_inverse:如果為true,返回去重數組的下標,它可以用於重構輸入數組return_counts:如果為true,返回去重數組中的元素在原數組中的出現次數
例子
import numpy as np a = np.array([5,2,6,2,7,5,6,8,2,9]) print '第一個數組:' print a print '\n' print '第一個數組的去重值:' u = np.unique(a) print u print '\n' print '去重數組的索引數組:' u,indices = np.unique(a, return_index = True) print indices print '\n' print '我們可以看到每個和原數組下標對應的數值:' print a print '\n' print '去重數組的下標:' u,indices = np.unique(a,return_inverse = True) print u print '\n' print '下標為:' print indices print '\n' print '使用下標重構原數組:' print u[indices] print '\n' print '返回去重元素的重復數量:' u,indices = np.unique(a,return_counts = True) print u print indices
輸出如下:
第一個數組: [5 2 6 2 7 5 6 8 2 9] 第一個數組的去重值: [2 5 6 7 8 9] 去重數組的索引數組: [1 0 2 4 7 9] 我們可以看到每個和原數組下標對應的數值: [5 2 6 2 7 5 6 8 2 9] 去重數組的下標: [2 5 6 7 8 9] 下標為: [1 0 2 0 3 1 2 4 0 5] 使用下標重構原數組: [5 2 6 2 7 5 6 8 2 9] 返回唯一元素的重復數量: [2 5 6 7 8 9] [3 2 2 1 1 1]
NumPy - 位操作
下面是 NumPy 包中可用的位操作函數。
| 序號 | 操作及描述 |
|---|---|
| 1. | bitwise_and 對數組元素執行位與操作 |
| 2. | bitwise_or 對數組元素執行位或操作 |
| 3. | invert 計算位非 |
| 4. | left_shift 向左移動二進制表示的位 |
| 5. | right_shift 向右移動二進制表示的位 |
bitwise_and
通過np.bitwise_and()函數對輸入數組中的整數的二進制表示的相應位執行位與運算。
例子
import numpy as np print '13 和 17 的二進制形式:' a,b = 13,17 print bin(a), bin(b) print '\n' print '13 和 17 的位與:' print np.bitwise_and(13, 17)
輸出如下:
13 和 17 的二進制形式:
0b1101 0b10001
13 和 17 的位與:
1
你可以使用下表驗證此輸出。 考慮下面的位與真值表。
| A | B | AND |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 0 | 0 |
| 0 | 1 | 0 |
| 0 | 0 | 0 |
| | | 1 | 1 | 0 | 1 |
| --- | --- |
| AND |
| | 1 | 0 | 0 | 0 | 1 |
| result | 0 | 0 | 0 | 0 | 1 |
bitwise_or
通過np.bitwise_or()函數對輸入數組中的整數的二進制表示的相應位執行位或運算。
例子
import numpy as np a,b = 13,17 print '13 和 17 的二進制形式:' print bin(a), bin(b) print '13 和 17 的位或:' print np.bitwise_or(13, 17)
輸出如下:
13 和 17 的二進制形式:
0b1101 0b10001
13 和 17 的位或:
29
你可以使用下表驗證此輸出。 考慮下面的位或真值表。
| A | B | OR |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 0 | 1 |
| 0 | 1 | 1 |
| 0 | 0 | 0 |
| | | 1 | 1 | 0 | 1 |
| --- | --- |
| OR |
| | 1 | 0 | 0 | 0 | 1 |
| result | 1 | 1 | 1 | 0 | 1 |
invert
此函數計算輸入數組中整數的位非結果。 對於有符號整數,返回補碼。
例子
import numpy as np print '13 的位反轉,其中 ndarray 的 dtype 是 uint8:' print np.invert(np.array([13], dtype = np.uint8)) print '\n' # 比較 13 和 242 的二進制表示,我們發現了位的反轉 print '13 的二進制表示:' print np.binary_repr(13, width = 8) print '\n' print '242 的二進制表示:' print np.binary_repr(242, width = 8)
輸出如下:
13 的位反轉,其中 ndarray 的 dtype 是 uint8: [242] 13 的二進制表示: 00001101 242 的二進制表示: 11110010
請注意,np.binary_repr()函數返回給定寬度中十進制數的二進制表示。
left_shift
numpy.left shift()函數將數組元素的二進制表示中的位向左移動到指定位置,右側附加相等數量的 0。
例如,
import numpy as np print '將 10 左移兩位:' print np.left_shift(10,2) print '\n' print '10 的二進制表示:' print np.binary_repr(10, width = 8) print '\n' print '40 的二進制表示:' print np.binary_repr(40, width = 8) # '00001010' 中的兩位移動到了左邊,並在右邊添加了兩個 0。
輸出如下:
將 10 左移兩位:
40
10 的二進制表示:
00001010
40 的二進制表示:
00101000
right_shift
numpy.right_shift()函數將數組元素的二進制表示中的位向右移動到指定位置,左側附加相等數量的 0。
import numpy as np print '將 40 右移兩位:' print np.right_shift(40,2) print '\n' print '40 的二進制表示:' print np.binary_repr(40, width = 8) print '\n' print '10 的二進制表示:' print np.binary_repr(10, width = 8) # '00001010' 中的兩位移動到了右邊,並在左邊添加了兩個 0。
輸出如下:
將 40 右移兩位:
10
40 的二進制表示:
00101000
10 的二進制表示:
00001010
NumPy - 字符串函數
以下函數用於對dtype為numpy.string_或numpy.unicode_的數組執行向量化字符串操作。 它們基於 Python 內置庫中的標准字符串函數。
| 序號 | 函數及描述 |
|---|---|
| 1. | add() 返回兩個str或Unicode數組的逐個字符串連接 |
| 2. | multiply() 返回按元素多重連接后的字符串 |
| 3. | center() 返回給定字符串的副本,其中元素位於特定字符串的中央 |
| 4. | capitalize() 返回給定字符串的副本,其中只有第一個字符串大寫 |
| 5. | title() 返回字符串或 Unicode 的按元素標題轉換版本 |
| 6. | lower() 返回一個數組,其元素轉換為小寫 |
| 7. | upper() 返回一個數組,其元素轉換為大寫 |
| 8. | split() 返回字符串中的單詞列表,並使用分隔符來分割 |
| 9. | splitlines() 返回元素中的行列表,以換行符分割 |
| 10. | strip() 返回數組副本,其中元素移除了開頭或者結尾處的特定字符 |
| 11. | join() 返回一個字符串,它是序列中字符串的連接 |
| 12. | replace() 返回字符串的副本,其中所有子字符串的出現位置都被新字符串取代 |
| 13. | decode() 按元素調用str.decode |
| 14. | encode() 按元素調用str.encode |
這些函數在字符數組類(numpy.char)中定義。 較舊的 Numarray 包包含chararray類。 numpy.char類中的上述函數在執行向量化字符串操作時非常有用。
numpy.char.add()
函數執行按元素的字符串連接。
import numpy as np print '連接兩個字符串:' print np.char.add(['hello'],[' xyz']) print '\n' print '連接示例:' print np.char.add(['hello', 'hi'],[' abc', ' xyz'])
輸出如下:
連接兩個字符串:
['hello xyz']
連接示例:
['hello abc' 'hi xyz']
numpy.char.multiply()
這個函數執行多重連接。
import numpy as np print np.char.multiply('Hello ',3)
輸出如下:
Hello Hello Hello
numpy.char.center()
此函數返回所需寬度的數組,以便輸入字符串位於中心,並使用fillchar在左側和右側進行填充。
import numpy as np # np.char.center(arr, width,fillchar) print np.char.center('hello', 20,fillchar = '*')
輸出如下:
*******hello********
numpy.char.capitalize()
函數返回字符串的副本,其中第一個字母大寫
import numpy as np print np.char.capitalize('hello world')
輸出如下:
Hello world
numpy.char.title()
返回輸入字符串的按元素標題轉換版本,其中每個單詞的首字母都大寫。
import numpy as np print np.char.title('hello how are you?')
輸出如下:
Hello How Are You?
numpy.char.lower()
函數返回一個數組,其元素轉換為小寫。它對每個元素調用str.lower。
import numpy as np print np.char.lower(['HELLO','WORLD']) print np.char.lower('HELLO')
輸出如下:
['hello' 'world']
hello
numpy.char.upper()
函數返回一個數組,其元素轉換為大寫。它對每個元素調用str.upper。
import numpy as np print np.char.upper('hello') print np.char.upper(['hello','world'])
輸出如下:
HELLO
['HELLO' 'WORLD']
numpy.char.split()
此函數返回輸入字符串中的單詞列表。 默認情況下,空格用作分隔符。 否則,指定的分隔符字符用於分割字符串。
import numpy as np print np.char.split ('hello how are you?') print np.char.split ('TutorialsPoint,Hyderabad,Telangana', sep = ',')
輸出如下:
['hello', 'how', 'are', 'you?']
['TutorialsPoint', 'Hyderabad', 'Telangana']
numpy.char.splitlines()
函數返回數組中元素的單詞列表,以換行符分割。
import numpy as np print np.char.splitlines('hello\nhow are you?') print np.char.splitlines('hello\rhow are you?')
輸出如下:
['hello', 'how are you?']
['hello', 'how are you?']
'\n','\r','\r\n'都會用作換行符。
numpy.char.strip()
函數返回數組的副本,其中元素移除了開頭或結尾處的特定字符。
import numpy as np print np.char.strip('ashok arora','a') print np.char.strip(['arora','admin','java'],'a')
輸出如下:
shok aror
['ror' 'dmin' 'jav']
numpy.char.join()
這個函數返回一個字符串,其中單個字符由特定的分隔符連接。
import numpy as np print np.char.join(':','dmy') print np.char.join([':','-'],['dmy','ymd'])
輸出如下:
d:m:y ['d:m:y' 'y-m-d']
numpy.char.replace()
這個函數返回字符串副本,其中所有字符序列的出現位置都被另一個給定的字符序列取代。
import numpy as np print np.char.replace ('He is a good boy', 'is', 'was')
輸出如下:
He was a good boy
numpy.char.decode()
這個函數在給定的字符串中使用特定編碼調用str.decode()。
import numpy as np a = np.char.encode('hello', 'cp500') print a print np.char.decode(a,'cp500')
輸出如下:
\x88\x85\x93\x93\x96
hello
numpy.char.encode()
此函數對數組中的每個元素調用str.encode函數。 默認編碼是utf_8,可以使用標准 Python 庫中的編解碼器。
import numpy as np a = np.char.encode('hello', 'cp500') print a
輸出如下:
\x88\x85\x93\x93\x96
NumPy - 算數函數
很容易理解的是,NumPy 包含大量的各種數學運算功能。 NumPy 提供標准的三角函數,算術運算的函數,復數處理函數等。
三角函數
NumPy 擁有標准的三角函數,它為弧度制單位的給定角度返回三角函數比值。
示例
import numpy as np a = np.array([0,30,45,60,90]) print '不同角度的正弦值:' # 通過乘 pi/180 轉化為弧度 print np.sin(a*np.pi/180) print '\n' print '數組中角度的余弦值:' print np.cos(a*np.pi/180) print '\n' print '數組中角度的正切值:' print np.tan(a*np.pi/180)
輸出如下:
不同角度的正弦值:
[ 0. 0.5 0.70710678 0.8660254 1. ]
數組中角度的余弦值:
[ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
6.12323400e-17]
數組中角度的正切值:
[ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
1.63312394e+16]
arcsin,arccos,和arctan函數返回給定角度的sin,cos和tan的反三角函數。 這些函數的結果可以通過numpy.degrees()函數通過將弧度制轉換為角度制來驗證。
示例
import numpy as np a = np.array([0,30,45,60,90]) print '含有正弦值的數組:' sin = np.sin(a*np.pi/180) print sin print '\n' print '計算角度的反正弦,返回值以弧度為單位:' inv = np.arcsin(sin) print inv print '\n' print '通過轉化為角度制來檢查結果:' print np.degrees(inv) print '\n' print 'arccos 和 arctan 函數行為類似:' cos = np.cos(a*np.pi/180) print cos print '\n' print '反余弦:' inv = np.arccos(cos) print inv print '\n' print '角度制單位:' print np.degrees(inv) print '\n' print 'tan 函數:' tan = np.tan(a*np.pi/180) print tan print '\n' print '反正切:' inv = np.arctan(tan) print inv print '\n' print '角度制單位:' print np.degrees(inv)
輸出如下:
含有正弦值的數組: [ 0. 0.5 0.70710678 0.8660254 1. ] 計算角度的反正弦,返回值以弧度制為單位: [ 0. 0.52359878 0.78539816 1.04719755 1.57079633] 通過轉化為角度制來檢查結果: [ 0. 30. 45. 60. 90.] arccos 和 arctan 函數行為類似: [ 1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01 6.12323400e-17] 反余弦: [ 0. 0.52359878 0.78539816 1.04719755 1.57079633] 角度制單位: [ 0. 30. 45. 60. 90.] tan 函數: [ 0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00 1.63312394e+16] 反正切: [ 0. 0.52359878 0.78539816 1.04719755 1.57079633] 角度制單位: [ 0. 30. 45. 60. 90.]
舍入函數
numpy.around()
這個函數返回四舍五入到所需精度的值。 該函數接受以下參數。
numpy.around(a,decimals)
其中:
| 序號 | 參數及描述 |
|---|---|
| 1. | a 輸入數組 |
| 2. | decimals 要舍入的小數位數。 默認值為0。 如果為負,整數將四舍五入到小數點左側的位置 |
示例
import numpy as np a = np.array([1.0,5.55, 123, 0.567, 25.532]) print '原數組:' print a print '\n' print '舍入后:' print np.around(a) print np.around(a, decimals = 1) print np.around(a, decimals = -1)
輸出如下:
原數組: [ 1. 5.55 123. 0.567 25.532] 舍入后: [ 1. 6. 123. 1. 26. ] [ 1. 5.6 123. 0.6 25.5] [ 0. 10. 120. 0. 30. ]
numpy.floor()
此函數返回不大於輸入參數的最大整數。 即標量x 的下限是最大的整數i ,使得i <= x。 注意在Python中,向下取整總是從 0 舍入。
示例
import numpy as np a = np.array([-1.7, 1.5, -0.2, 0.6, 10]) print '提供的數組:' print a print '\n' print '修改后的數組:' print np.floor(a)
輸出如下:
提供的數組: [ -1.7 1.5 -0.2 0.6 10. ] 修改后的數組: [ -2. 1. -1. 0. 10.]
numpy.ceil()
ceil()函數返回輸入值的上限,即,標量x的上限是最小的整數i ,使得i> = x。
示例
import numpy as np a = np.array([-1.7, 1.5, -0.2, 0.6, 10]) print '提供的數組:' print a print '\n' print '修改后的數組:' print np.ceil(a)
輸出如下:
提供的數組: [ -1.7 1.5 -0.2 0.6 10. ] 修改后的數組: [ -1. 2. -0. 1. 10.]
NumPy - 算數運算
用於執行算術運算(如add(),subtract(),multiply()和divide())的輸入數組必須具有相同的形狀或符合數組廣播規則。
示例
import numpy as np a = np.arange(9, dtype = np.float_).reshape(3,3) print '第一個數組:' print a print '\n' print '第二個數組:' b = np.array([10,10,10]) print b print '\n' print '兩個數組相加:' print np.add(a,b) print '\n' print '兩個數組相減:' print np.subtract(a,b) print '\n' print '兩個數組相乘:' print np.multiply(a,b) print '\n' print '兩個數組相除:' print np.divide(a,b)
輸出如下:
第一個數組: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] 第二個數組: [10 10 10] 兩個數組相加: [[ 10. 11. 12.] [ 13. 14. 15.] [ 16. 17. 18.]] 兩個數組相減: [[-10. -9. -8.] [ -7. -6. -5.] [ -4. -3. -2.]] 兩個數組相乘: [[ 0. 10. 20.] [ 30. 40. 50.] [ 60. 70. 80.]] 兩個數組相除: [[ 0. 0.1 0.2] [ 0.3 0.4 0.5] [ 0.6 0.7 0.8]]
讓我們現在來討論 NumPy 中提供的一些其他重要的算術函數。
numpy.reciprocal()
此函數返回參數逐元素的倒數,。 由於 Python 處理整數除法的方式,對於絕對值大於 1 的整數元素,結果始終為 0, 對於整數 0,則發出溢出警告。
示例
import numpy as np a = np.array([0.25, 1.33, 1, 0, 100]) print '我們的數組是:' print a print '\n' print '調用 reciprocal 函數:' print np.reciprocal(a) print '\n' b = np.array([100], dtype = int) print '第二個數組:' print b print '\n' print '調用 reciprocal 函數:' print np.reciprocal(b)
輸出如下:
我們的數組是: [ 0.25 1.33 1. 0. 100. ] 調用 reciprocal 函數: main.py:9: RuntimeWarning: divide by zero encountered in reciprocal print np.reciprocal(a) [ 4. 0.7518797 1. inf 0.01 ] 第二個數組: [100] 調用 reciprocal 函數: [0]
numpy.power()
此函數將第一個輸入數組中的元素作為底數,計算它與第二個輸入數組中相應元素的冪。
import numpy as np a = np.array([10,100,1000]) print '我們的數組是;' print a print '\n' print '調用 power 函數:' print np.power(a,2) print '\n' print '第二個數組:' b = np.array([1,2,3]) print b print '\n' print '再次調用 power 函數:' print np.power(a,b)
輸出如下:
我們的數組是; [ 10 100 1000] 調用 power 函數: [ 100 10000 1000000] 第二個數組: [1 2 3] 再次調用 power 函數: [ 10 10000 1000000000]
numpy.mod()
此函數返回輸入數組中相應元素的除法余數。 函數numpy.remainder()也產生相同的結果。
import numpy as np a = np.array([10,20,30]) b = np.array([3,5,7]) print '第一個數組:' print a print '\n' print '第二個數組:' print b print '\n' print '調用 mod() 函數:' print np.mod(a,b) print '\n' print '調用 remainder() 函數:' print np.remainder(a,b)
輸出如下:
第一個數組: [10 20 30] 第二個數組: [3 5 7] 調用 mod() 函數: [1 0 2] 調用 remainder() 函數: [1 0 2]
以下函數用於對含有復數的數組執行操作。
-
numpy.real()返回復數類型參數的實部。 -
numpy.imag()返回復數類型參數的虛部。 -
numpy.conj()返回通過改變虛部的符號而獲得的共軛復數。 -
numpy.angle()返回復數參數的角度。 函數的參數是degree。 如果為true,返回的角度以角度制來表示,否則為以弧度制來表示。
import numpy as np a = np.array([-5.6j, 0.2j, 11. , 1+1j]) print '我們的數組是:' print a print '\n' print '調用 real() 函數:' print np.real(a) print '\n' print '調用 imag() 函數:' print np.imag(a) print '\n' print '調用 conj() 函數:' print np.conj(a) print '\n' print '調用 angle() 函數:' print np.angle(a) print '\n' print '再次調用 angle() 函數(以角度制返回):' print np.angle(a, deg = True)
輸出如下:
我們的數組是: [ 0.-5.6j 0.+0.2j 11.+0.j 1.+1.j ] 調用 real() 函數: [ 0. 0. 11. 1.] 調用 imag() 函數: [-5.6 0.2 0. 1. ] 調用 conj() 函數: [ 0.+5.6j 0.-0.2j 11.-0.j 1.-1.j ] 調用 angle() 函數: [-1.57079633 1.57079633 0. 0.78539816] 再次調用 angle() 函數(以角度制返回): [-90. 90. 0. 45.]
NumPy - 統計函數
NumPy 有很多有用的統計函數,用於從數組中給定的元素中查找最小,最大,百分標准差和方差等。 函數說明如下:
numpy.amin() 和 numpy.amax()
這些函數從給定數組中的元素沿指定軸返回最小值和最大值。
示例
import numpy as np a = np.array([[3,7,5],[8,4,3],[2,4,9]]) print '我們的數組是:' print a print '\n' print '調用 amin() 函數:' print np.amin(a,1) print '\n' print '再次調用 amin() 函數:' print np.amin(a,0) print '\n' print '調用 amax() 函數:' print np.amax(a) print '\n' print '再次調用 amax() 函數:' print np.amax(a, axis = 0)
輸出如下:
我們的數組是: [[3 7 5] [8 4 3] [2 4 9]] 調用 amin() 函數: [3 3 2] 再次調用 amin() 函數: [2 4 3] 調用 amax() 函數: 9 再次調用 amax() 函數: [8 7 9]
numpy.ptp()
numpy.ptp()函數返回沿軸的值的范圍(最大值 - 最小值)。
import numpy as np a = np.array([[3,7,5],[8,4,3],[2,4,9]]) print '我們的數組是:' print a print '\n' print '調用 ptp() 函數:' print np.ptp(a) print '\n' print '沿軸 1 調用 ptp() 函數:' print np.ptp(a, axis = 1) print '\n' print '沿軸 0 調用 ptp() 函數:' print np.ptp(a, axis = 0)
輸出如下:
我們的數組是: [[3 7 5] [8 4 3] [2 4 9]] 調用 ptp() 函數: 7 沿軸 1 調用 ptp() 函數: [4 5 7] 沿軸 0 調用 ptp() 函數: [6 3 6]
numpy.percentile()
百分位數是統計中使用的度量,表示小於這個值得觀察值占某個百分比。 函數numpy.percentile()接受以下參數。
numpy.percentile(a, q, axis)
其中:
| 序號 | 參數及描述 |
|---|---|
| 1. | a 輸入數組 |
| 2. | q 要計算的百分位數,在 0 ~ 100 之間 |
| 3. | axis 沿着它計算百分位數的軸 |
示例
import numpy as np a = np.array([[30,40,70],[80,20,10],[50,90,60]]) print '我們的數組是:' print a print '\n' print '調用 percentile() 函數:' print np.percentile(a,50) print '\n' print '沿軸 1 調用 percentile() 函數:' print np.percentile(a,50, axis = 1) print '\n' print '沿軸 0 調用 percentile() 函數:' print np.percentile(a,50, axis = 0)
輸出如下:
我們的數組是: [[30 40 70] [80 20 10] [50 90 60]] 調用 percentile() 函數: 50.0 沿軸 1 調用 percentile() 函數: [ 40. 20. 60.] 沿軸 0 調用 percentile() 函數: [ 50. 40. 60.]
numpy.median()
中值定義為將數據樣本的上半部分與下半部分分開的值。 numpy.median()函數的用法如下面的程序所示。
示例
import numpy as np a = np.array([[30,65,70],[80,95,10],[50,90,60]]) print '我們的數組是:' print a print '\n' print '調用 median() 函數:' print np.median(a) print '\n' print '沿軸 0 調用 median() 函數:' print np.median(a, axis = 0) print '\n' print '沿軸 1 調用 median() 函數:' print np.median(a, axis = 1)
輸出如下:
我們的數組是: [[30 65 70] [80 95 10] [50 90 60]] 調用 median() 函數: 65.0 沿軸 0 調用 median() 函數: [ 50. 90. 60.] 沿軸 1 調用 median() 函數: [ 65. 80. 60.]
numpy.mean()
算術平均值是沿軸的元素的總和除以元素的數量。 numpy.mean()函數返回數組中元素的算術平均值。 如果提供了軸,則沿其計算。
示例
import numpy as np a = np.array([[1,2,3],[3,4,5],[4,5,6]]) print '我們的數組是:' print a print '\n' print '調用 mean() 函數:' print np.mean(a) print '\n' print '沿軸 0 調用 mean() 函數:' print np.mean(a, axis = 0) print '\n' print '沿軸 1 調用 mean() 函數:' print np.mean(a, axis = 1)
輸出如下:
我們的數組是: [[1 2 3] [3 4 5] [4 5 6]] 調用 mean() 函數: 3.66666666667 沿軸 0 調用 mean() 函數: [ 2.66666667 3.66666667 4.66666667] 沿軸 1 調用 mean() 函數: [ 2. 4. 5.]
numpy.average()
加權平均值是由每個分量乘以反映其重要性的因子得到的平均值。 numpy.average()函數根據在另一個數組中給出的各自的權重計算數組中元素的加權平均值。 該函數可以接受一個軸參數。 如果沒有指定軸,則數組會被展開。
考慮數組[1,2,3,4]和相應的權重[4,3,2,1],通過將相應元素的乘積相加,並將和除以權重的和,來計算加權平均值。
加權平均值 = (1*4+2*3+3*2+4*1)/(4+3+2+1)
示例
import numpy as np a = np.array([1,2,3,4]) print '我們的數組是:' print a print '\n' print '調用 average() 函數:' print np.average(a) print '\n' # 不指定權重時相當於 mean 函數 wts = np.array([4,3,2,1]) print '再次調用 average() 函數:' print np.average(a,weights = wts) print '\n' # 如果 returned 參數設為 true,則返回權重的和 print '權重的和:' print np.average([1,2,3, 4],weights = [4,3,2,1], returned = True)
輸出如下:
我們的數組是: [1 2 3 4] 調用 average() 函數: 2.5 再次調用 average() 函數: 2.0 權重的和: (2.0, 10.0)
在多維數組中,可以指定用於計算的軸。
示例
import numpy as np a = np.arange(6).reshape(3,2) print '我們的數組是:' print a print '\n' print '修改后的數組:' wt = np.array([3,5]) print np.average(a, axis = 1, weights = wt) print '\n' print '修改后的數組:' print np.average(a, axis = 1, weights = wt, returned = True)
輸出如下:
我們的數組是: [[0 1] [2 3] [4 5]] 修改后的數組: [ 0.625 2.625 4.625] 修改后的數組: (array([ 0.625, 2.625, 4.625]), array([ 8., 8., 8.]))
標准差
標准差是與均值的偏差的平方的平均值的平方根。 標准差公式如下:
std = sqrt(mean((x - x.mean())**2))
如果數組是[1,2,3,4],則其平均值為2.5。 因此,差的平方是[2.25,0.25,0.25,2.25],並且其平均值的平方根除以4,即sqrt(5/4)是1.1180339887498949。
示例
import numpy as np print np.std([1,2,3,4])
輸出如下:
1.1180339887498949
方差
方差是偏差的平方的平均值,即mean((x - x.mean())** 2)。 換句話說,標准差是方差的平方根。
示例
import numpy as np print np.var([1,2,3,4])
輸出如下:
1.25
NumPy - 排序、搜索和計數函數
NumPy中提供了各種排序相關功能。 這些排序函數實現不同的排序算法,每個排序算法的特征在於執行速度,最壞情況性能,所需的工作空間和算法的穩定性。 下表顯示了三種排序算法的比較。
| 種類 | 速度 | 最壞情況 | 工作空間 | 穩定性 |
|---|---|---|---|---|
'quicksort'(快速排序) |
1 | O(n^2) |
0 | 否 |
'mergesort'(歸並排序) |
2 | O(n*log(n)) |
~n/2 | 是 |
'heapsort'(堆排序) |
3 | O(n*log(n)) |
0 | 否 |
numpy.sort()
sort()函數返回輸入數組的排序副本。 它有以下參數:
numpy.sort(a, axis, kind, order)
其中:
| 序號 | 參數及描述 |
|---|---|
| 1. | a 要排序的數組 |
| 2. | axis 沿着它排序數組的軸,如果沒有數組會被展開,沿着最后的軸排序 |
| 3. | kind 默認為'quicksort'(快速排序) |
| 4. | order 如果數組包含字段,則是要排序的字段 |
示例
import numpy as np a = np.array([[3,7],[9,1]]) print '我們的數組是:' print a print '\n' print '調用 sort() 函數:' print np.sort(a) print '\n' print '沿軸 0 排序:' print np.sort(a, axis = 0) print '\n' # 在 sort 函數中排序字段 dt = np.dtype([('name', 'S10'),('age', int)]) a = np.array([("raju",21),("anil",25),("ravi", 17), ("amar",27)], dtype = dt) print '我們的數組是:' print a print '\n' print '按 name 排序:' print np.sort(a, order = 'name')
輸出如下:
我們的數組是:
[[3 7]
[9 1]]
調用 sort() 函數:
[[3 7]
[1 9]]
沿軸 0 排序:
[[3 1]
[9 7]]
我們的數組是:
[('raju', 21) ('anil', 25) ('ravi', 17) ('amar', 27)]
按 name 排序:
[('amar', 27) ('anil', 25) ('raju', 21) ('ravi', 17)]
numpy.argsort()
numpy.argsort()函數對輸入數組沿給定軸執行間接排序,並使用指定排序類型返回數據的索引數組。 這個索引數組用於構造排序后的數組。
示例
import numpy as np x = np.array([3, 1, 2]) print '我們的數組是:' print x print '\n' print '對 x 調用 argsort() 函數:' y = np.argsort(x) print y print '\n' print '以排序后的順序重構原數組:' print x[y] print '\n' print '使用循環重構原數組:' for i in y: print x[i],
輸出如下:
我們的數組是: [3 1 2] 對 x 調用 argsort() 函數: [1 2 0] 以排序后的順序重構原數組: [1 2 3] 使用循環重構原數組: 1 2 3
numpy.lexsort()
函數使用鍵序列執行間接排序。 鍵可以看作是電子表格中的一列。 該函數返回一個索引數組,使用它可以獲得排序數據。 注意,最后一個鍵恰好是 sort 的主鍵。
示例
import numpy as np nm = ('raju','anil','ravi','amar') dv = ('f.y.', 's.y.', 's.y.', 'f.y.') ind = np.lexsort((dv,nm)) print '調用 lexsort() 函數:' print ind print '\n' print '使用這個索引來獲取排序后的數據:' print [nm[i] + ", " + dv[i] for i in ind]
輸出如下:
調用 lexsort() 函數:
[3 1 0 2]
使用這個索引來獲取排序后的數據:
['amar, f.y.', 'anil, s.y.', 'raju, f.y.', 'ravi, s.y.']
NumPy 模塊有一些用於在數組內搜索的函數。 提供了用於找到最大值,最小值以及滿足給定條件的元素的函數。
numpy.argmax() 和 numpy.argmin()
這兩個函數分別沿給定軸返回最大和最小元素的索引。
示例
import numpy as np a = np.array([[30,40,70],[80,20,10],[50,90,60]]) print '我們的數組是:' print a print '\n' print '調用 argmax() 函數:' print np.argmax(a) print '\n' print '展開數組:' print a.flatten() print '\n' print '沿軸 0 的最大值索引:' maxindex = np.argmax(a, axis = 0) print maxindex print '\n' print '沿軸 1 的最大值索引:' maxindex = np.argmax(a, axis = 1) print maxindex print '\n' print '調用 argmin() 函數:' minindex = np.argmin(a) print minindex print '\n' print '展開數組中的最小值:' print a.flatten()[minindex] print '\n' print '沿軸 0 的最小值索引:' minindex = np.argmin(a, axis = 0) print minindex print '\n' print '沿軸 1 的最小值索引:' minindex = np.argmin(a, axis = 1) print minindex
輸出如下:
我們的數組是: [[30 40 70] [80 20 10] [50 90 60]] 調用 argmax() 函數: 7 展開數組: [30 40 70 80 20 10 50 90 60] 沿軸 0 的最大值索引: [1 2 0] 沿軸 1 的最大值索引: [2 0 1] 調用 argmin() 函數: 5 展開數組中的最小值: 10 沿軸 0 的最小值索引: [0 1 1] 沿軸 1 的最小值索引: [0 2 0]
numpy.nonzero()
numpy.nonzero()函數返回輸入數組中非零元素的索引。
示例
import numpy as np a = np.array([[30,40,0],[0,20,10],[50,0,60]]) print '我們的數組是:' print a print '\n' print '調用 nonzero() 函數:' print np.nonzero (a)
輸出如下:
我們的數組是: [[30 40 0] [ 0 20 10] [50 0 60]] 調用 nonzero() 函數: (array([0, 0, 1, 1, 2, 2]), array([0, 1, 1, 2, 0, 2]))
numpy.where()
where()函數返回輸入數組中滿足給定條件的元素的索引。
示例
import numpy as np x = np.arange(9.).reshape(3, 3) print '我們的數組是:' print x print '大於 3 的元素的索引:' y = np.where(x > 3) print y print '使用這些索引來獲取滿足條件的元素:' print x[y]
輸出如下:
我們的數組是: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] 大於 3 的元素的索引: (array([1, 1, 2, 2, 2]), array([1, 2, 0, 1, 2])) 使用這些索引來獲取滿足條件的元素: [ 4. 5. 6. 7. 8.]
numpy.extract()
extract()函數返回滿足任何條件的元素。
import numpy as np x = np.arange(9.).reshape(3, 3) print '我們的數組是:' print x # 定義條件 condition = np.mod(x,2) == 0 print '按元素的條件值:' print condition print '使用條件提取元素:' print np.extract(condition, x)
輸出如下:
我們的數組是: [[ 0. 1. 2.] [ 3. 4. 5.] [ 6. 7. 8.]] 按元素的條件值: [[ True False True] [False True False] [ True False True]] 使用條件提取元素: [ 0. 2. 4. 6. 8.]
NumPy - 字節交換
我們已經看到,存儲在計算機內存中的數據取決於 CPU 使用的架構。 它可以是小端(最小有效位存儲在最小地址中)或大端(最小有效字節存儲在最大地址中)。
numpy.ndarray.byteswap()
numpy.ndarray.byteswap()函數在兩個表示:大端和小端之間切換。
import numpy as np a = np.array([1, 256, 8755], dtype = np.int16) print '我們的數組是:' print a print '以十六進制表示內存中的數據:' print map(hex,a) # byteswap() 函數通過傳入 true 來原地交換 print '調用 byteswap() 函數:' print a.byteswap(True) print '十六進制形式:' print map(hex,a) # 我們可以看到字節已經交換了
輸出如下:
我們的數組是:
[1 256 8755]
以十六進制表示內存中的數據:
['0x1', '0x100', '0x2233']
調用 byteswap() 函數:
[256 1 13090]
十六進制形式:
['0x100', '0x1', '0x3322']
NumPy - 副本和視圖
在執行函數時,其中一些返回輸入數組的副本,而另一些返回視圖。 當內容物理存儲在另一個位置時,稱為副本。 另一方面,如果提供了相同內存內容的不同視圖,我們將其稱為視圖。
無復制
簡單的賦值不會創建數組對象的副本。 相反,它使用原始數組的相同id()來訪問它。 id()返回 Python 對象的通用標識符,類似於 C 中的指針。
此外,一個數組的任何變化都反映在另一個數組上。 例如,一個數組的形狀改變也會改變另一個數組的形狀。
示例
import numpy as np a = np.arange(6) print '我們的數組是:' print a print '調用 id() 函數:' print id(a) print 'a 賦值給 b:' b = a print b print 'b 擁有相同 id():' print id(b) print '修改 b 的形狀:' b.shape = 3,2 print b print 'a 的形狀也修改了:' print a
輸出如下:
我們的數組是: [0 1 2 3 4 5] 調用 id() 函數: 139747815479536 a 賦值給 b: [0 1 2 3 4 5] b 擁有相同 id(): 139747815479536 修改 b 的形狀: [[0 1] [2 3] [4 5]] a 的形狀也修改了: [[0 1] [2 3] [4 5]]
視圖或淺復制
NumPy 擁有ndarray.view()方法,它是一個新的數組對象,並可查看原始數組的相同數據。 與前一種情況不同,新數組的維數更改不會更改原始數據的維數。
示例
import numpy as np # 最開始 a 是個 3X2 的數組 a = np.arange(6).reshape(3,2) print '數組 a:' print a print '創建 a 的視圖:' b = a.view() print b print '兩個數組的 id() 不同:' print 'a 的 id():' print id(a) print 'b 的 id():' print id(b) # 修改 b 的形狀,並不會修改 a b.shape = 2,3 print 'b 的形狀:' print b print 'a 的形狀:' print a
輸出如下:
數組 a: [[0 1] [2 3] [4 5]] 創建 a 的視圖: [[0 1] [2 3] [4 5]] 兩個數組的 id() 不同: a 的 id(): 140424307227264 b 的 id(): 140424151696288 b 的形狀: [[0 1 2] [3 4 5]] a 的形狀: [[0 1] [2 3] [4 5]]
數組的切片也會創建視圖:
示例
import numpy as np a = np.array([[10,10], [2,3], [4,5]]) print '我們的數組:' print a print '創建切片:' s = a[:, :2] print s
輸出如下:
我們的數組: [[10 10] [ 2 3] [ 4 5]] 創建切片: [[10 10] [ 2 3] [ 4 5]]
深復制
ndarray.copy()函數創建一個深層副本。 它是數組及其數據的完整副本,不與原始數組共享。
示例
import numpy as np a = np.array([[10,10], [2,3], [4,5]]) print '數組 a:' print a print '創建 a 的深層副本:' b = a.copy() print '數組 b:' print b # b 與 a 不共享任何內容 print '我們能夠寫入 b 來寫入 a 嗎?' print b is a print '修改 b 的內容:' b[0,0] = 100 print '修改后的數組 b:' print b print 'a 保持不變:' print a
輸出如下:
數組 a: [[10 10] [ 2 3] [ 4 5]] 創建 a 的深層副本: 數組 b: [[10 10] [ 2 3] [ 4 5]] 我們能夠寫入 b 來寫入 a 嗎? False 修改 b 的內容: 修改后的數組 b: [[100 10] [ 2 3] [ 4 5]] a 保持不變: [[10 10] [ 2 3] [ 4 5]]
NumPy - 矩陣庫
NumPy 包包含一個 Matrix庫numpy.matlib。此模塊的函數返回矩陣而不是返回ndarray對象。
matlib.empty()
matlib.empty()函數返回一個新的矩陣,而不初始化元素。 該函數接受以下參數。
numpy.matlib.empty(shape, dtype, order)
其中:
| 序號 | 參數及描述 |
|---|---|
| 1. | shape 定義新矩陣形狀的整數或整數元組 |
| 2. | Dtype 可選,輸出的數據類型 |
| 3. | order C 或者 F |
示例
import numpy.matlib import numpy as np print np.matlib.empty((2,2)) # 填充為隨機數據
輸出如下:
[[ 2.12199579e-314, 4.24399158e-314]
[ 4.24399158e-314, 2.12199579e-314]]
numpy.matlib.zeros()
此函數返回以零填充的矩陣。
import numpy.matlib import numpy as np print np.matlib.zeros((2,2))
輸出如下:
[[ 0. 0.] [ 0. 0.]])
numpy.matlib.ones()
此函數返回以一填充的矩陣。
import numpy.matlib import numpy as np print np.matlib.ones((2,2))
輸出如下:
[[ 1. 1.]
[ 1. 1.]]
numpy.matlib.eye()
這個函數返回一個矩陣,對角線元素為 1,其他位置為零。 該函數接受以下參數。
numpy.matlib.eye(n, M,k, dtype)
其中:
| 序號 | 參數及描述 |
|---|---|
| 1. | n 返回矩陣的行數 |
| 2. | M 返回矩陣的列數,默認為n |
| 3. | k 對角線的索引 |
| 4. | dtype 輸出的數據類型 |
示例
import numpy.matlib import numpy as np print np.matlib.eye(n = 3, M = 4, k = 0, dtype = float)
輸出如下:
[[ 1. 0. 0. 0.] [ 0. 1. 0. 0.] [ 0. 0. 1. 0.]])
numpy.matlib.identity()
numpy.matlib.identity()函數返回給定大小的單位矩陣。單位矩陣是主對角線元素都為 1 的方陣。
import numpy.matlib import numpy as np print np.matlib.identity(5, dtype = float)
輸出如下:
[[ 1. 0. 0. 0. 0.]
[ 0. 1. 0. 0. 0.]
[ 0. 0. 1. 0. 0.]
[ 0. 0. 0. 1. 0.]
[ 0. 0. 0. 0. 1.]]
numpy.matlib.rand()
·numpy.matlib.rand()`函數返回給定大小的填充隨機值的矩陣。
示例
import numpy.matlib import numpy as np print np.matlib.rand(3,3)
輸出如下:
[[ 0.82674464 0.57206837 0.15497519]
[ 0.33857374 0.35742401 0.90895076]
[ 0.03968467 0.13962089 0.39665201]]
注意,矩陣總是二維的,而ndarray是一個 n 維數組。 兩個對象都是可互換的。
示例
import numpy.matlib import numpy as np i = np.matrix('1,2;3,4') print i
輸出如下:
[[1 2]
[3 4]]
示例
import numpy.matlib import numpy as np j = np.asarray(i) print j
輸出如下:
[[1 2]
[3 4]]
示例
import numpy.matlib import numpy as np k = np.asmatrix (j) print k
輸出如下:
[[1 2]
[3 4]]
NumPy - 線性代數
NumPy 包包含numpy.linalg模塊,提供線性代數所需的所有功能。 此模塊中的一些重要功能如下表所述。
| 序號 | 函數及描述 |
|---|---|
| 1. | dot 兩個數組的點積 |
| 2. | vdot 兩個向量的點積 |
| 3. | inner 兩個數組的內積 |
| 4. | matmul 兩個數組的矩陣積 |
| 5. | determinant 數組的行列式 |
| 6. | solve 求解線性矩陣方程 |
| 7. | inv 尋找矩陣的乘法逆矩陣 |
numpy.dot()
此函數返回兩個數組的點積。 對於二維向量,其等效於矩陣乘法。 對於一維數組,它是向量的內積。 對於 N 維數組,它是a的最后一個軸上的和與b的倒數第二個軸的乘積。
import numpy.matlib import numpy as np a = np.array([[1,2],[3,4]]) b = np.array([[11,12],[13,14]]) np.dot(a,b)
輸出如下:
[[37 40]
[85 92]]
要注意點積計算為:
[[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]]
numpy.vdot()
此函數返回兩個向量的點積。 如果第一個參數是復數,那么它的共軛復數會用於計算。 如果參數id是多維數組,它會被展開。
例子
import numpy as np a = np.array([[1,2],[3,4]]) b = np.array([[11,12],[13,14]]) print np.vdot(a,b)
輸出如下:
130
注意:1*11 + 2*12 + 3*13 + 4*14 = 130。
numpy.inner()
此函數返回一維數組的向量內積。 對於更高的維度,它返回最后一個軸上的和的乘積。
例子
import numpy as np print np.inner(np.array([1,2,3]),np.array([0,1,0])) # 等價於 1*0+2*1+3*0
輸出如下:
2
例子
# 多維數組示例 import numpy as np a = np.array([[1,2], [3,4]]) print '數組 a:' print a b = np.array([[11, 12], [13, 14]]) print '數組 b:' print b print '內積:' print np.inner(a,b)
輸出如下:
數組 a: [[1 2] [3 4]] 數組 b: [[11 12] [13 14]] 內積: [[35 41] [81 95]]
上面的例子中,內積計算如下:
1*11+2*12, 1*13+2*14
3*11+4*12, 3*13+4*14
numpy.matmul
numpy.matmul()函數返回兩個數組的矩陣乘積。 雖然它返回二維數組的正常乘積,但如果任一參數的維數大於2,則將其視為存在於最后兩個索引的矩陣的棧,並進行相應廣播。
另一方面,如果任一參數是一維數組,則通過在其維度上附加 1 來將其提升為矩陣,並在乘法之后被去除。
例子
# 對於二維數組,它就是矩陣乘法 import numpy.matlib import numpy as np a = [[1,0],[0,1]] b = [[4,1],[2,2]] print np.matmul(a,b)
輸出如下:
[[4 1]
[2 2]]
例子
# 二維和一維運算 import numpy.matlib import numpy as np a = [[1,0],[0,1]] b = [1,2] print np.matmul(a,b) print np.matmul(b,a)
輸出如下:
[1 2]
[1 2]
例子
# 維度大於二的數組 import numpy.matlib import numpy as np a = np.arange(8).reshape(2,2,2) b = np.arange(4).reshape(2,2) print np.matmul(a,b)
輸出如下:
[[[2 3]
[6 11]]
[[10 19]
[14 27]]]
numpy.linalg.det()
行列式在線性代數中是非常有用的值。 它從方陣的對角元素計算。 對於 2×2 矩陣,它是左上和右下元素的乘積與其他兩個的乘積的差。
換句話說,對於矩陣[[a,b],[c,d]],行列式計算為ad-bc。 較大的方陣被認為是 2×2 矩陣的組合。
numpy.linalg.det()函數計算輸入矩陣的行列式。
例子
import numpy as np a = np.array([[1,2], [3,4]]) print np.linalg.det(a)
輸出如下:
-2.0
例子
b = np.array([[6,1,1], [4, -2, 5], [2,8,7]]) print b print np.linalg.det(b) print 6*(-2*7 - 5*8) - 1*(4*7 - 5*2) + 1*(4*8 - -2*2)
輸出如下:
[[ 6 1 1]
[ 4 -2 5]
[ 2 8 7]]
-306.0
-306
numpy.linalg.solve()
numpy.linalg.solve()函數給出了矩陣形式的線性方程的解。
考慮以下線性方程:
x + y + z = 6
2y + 5z = -4
2x + 5y - z = 27
可以使用矩陣表示為:
如果矩陣成為A、X和B,方程變為:
AX = B
或
X = A^(-1)B
numpy.linalg.inv()
我們使用numpy.linalg.inv()函數來計算矩陣的逆。 矩陣的逆是這樣的,如果它乘以原始矩陣,則得到單位矩陣。
例子
import numpy as np x = np.array([[1,2],[3,4]]) y = np.linalg.inv(x) print x print y print np.dot(x,y)
輸出如下:
[[1 2]
[3 4]]
[[-2. 1. ]
[ 1.5 -0.5]]
[[ 1.00000000e+00 1.11022302e-16]
[ 0.00000000e+00 1.00000000e+00]]
例子
現在讓我們在示例中創建一個矩陣A的逆。
import numpy as np a = np.array([[1,1,1],[0,2,5],[2,5,-1]]) print '數組 a:' print a ainv = np.linalg.inv(a) print 'a 的逆:' print ainv print '矩陣 b:' b = np.array([[6],[-4],[27]]) print b print '計算:A^(-1)B:' x = np.linalg.solve(a,b) print x # 這就是線性方向 x = 5, y = 3, z = -2 的解
輸出如下:
數組 a: [[ 1 1 1] [ 0 2 5] [ 2 5 -1]] a 的逆: [[ 1.28571429 -0.28571429 -0.14285714] [-0.47619048 0.14285714 0.23809524] [ 0.19047619 0.14285714 -0.0952381 ]] 矩陣 b: [[ 6] [-4] [27]] 計算:A^(-1)B: [[ 5.] [ 3.] [-2.]]
結果也可以使用下列函數獲取
x = np.dot(ainv,b)
NumPy - Matplotlib
Matplotlib 是 Python 的繪圖庫。 它可與 NumPy 一起使用,提供了一種有效的 MatLab 開源替代方案。 它也可以和圖形工具包一起使用,如 PyQt 和 wxPython。
Matplotlib 模塊最初是由 John D. Hunter 編寫的。 自 2012 年以來,Michael Droettboom 是主要開發者。 目前,Matplotlib 1.5.1 是可用的穩定版本。 該軟件包可以二進制分發,其源代碼形式在 www.matplotlib.org 上提供。
通常,通過添加以下語句將包導入到 Python 腳本中:
from matplotlib import pyplot as plt
這里pyplot()是 matplotlib 庫中最重要的函數,用於繪制 2D 數據。 以下腳本繪制方程y = 2x + 5:
示例
import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y) plt.show()
ndarray對象x由np.arange()函數創建為x軸上的值。y軸上的對應值存儲在另一個數組對象y中。 這些值使用matplotlib軟件包的pyplot子模塊的plot()函數繪制。
圖形由show()函數展示。
上面的代碼應該產生以下輸出:
作為線性圖的替代,可以通過向plot()函數添加格式字符串來顯示離散值。 可以使用以下格式化字符。
| 字符 | 描述 | |
|---|---|---|
'-' |
實線樣式 | |
'--' |
短橫線樣式 | |
'-.' |
點划線樣式 | |
':' |
虛線樣式 | |
'.' |
點標記 | |
',' |
像素標記 | |
'o' |
圓標記 | |
'v' |
倒三角標記 | |
'^' |
正三角標記 | |
'<' |
左三角標記 | |
'>' |
右三角標記 | |
'1' |
下箭頭標記 | |
'2' |
上箭頭標記 | |
'3' |
左箭頭標記 | |
'4' |
右箭頭標記 | |
's' |
正方形標記 | |
'p' |
五邊形標記 | |
'*' |
星形標記 | |
'h' |
六邊形標記 1 | |
'H' |
六邊形標記 2 | |
'+' |
加號標記 | |
'x' |
X 標記 | |
'D' |
菱形標記 | |
'd' |
窄菱形標記 | |
| `' | '` | 豎直線標記 |
'_' |
水平線標記 |
還定義了以下顏色縮寫。
| 字符 | 顏色 |
|---|---|
'b' |
藍色 |
'g' |
綠色 |
'r' |
紅色 |
'c' |
青色 |
'm' |
品紅色 |
'y' |
黃色 |
'k' |
黑色 |
'w' |
白色 |
要顯示圓來代表點,而不是上面示例中的線,請使用ob作為plot()函數中的格式字符串。
示例
import numpy as np from matplotlib import pyplot as plt x = np.arange(1,11) y = 2 * x + 5 plt.title("Matplotlib demo") plt.xlabel("x axis caption") plt.ylabel("y axis caption") plt.plot(x,y,"ob") plt.show()
上面的代碼應該產生以下輸出:
繪制正弦波
以下腳本使用 matplotlib 生成正弦波圖。
示例
import numpy as np import matplotlib.pyplot as plt # 計算正弦曲線上點的 x 和 y 坐標 x = np.arange(0, 3 * np.pi, 0.1) y = np.sin(x) plt.title("sine wave form") # 使用 matplotlib 來繪制點 plt.plot(x, y) plt.show()
subplot()
subplot()函數允許你在同一圖中繪制不同的東西。 在下面的腳本中,繪制正弦和余弦值。
示例
import numpy as np import matplotlib.pyplot as plt # 計算正弦和余弦曲線上的點的 x 和 y 坐標 x = np.arange(0, 3 * np.pi, 0.1) y_sin = np.sin(x) y_cos = np.cos(x) # 建立 subplot 網格,高為 2,寬為 1 # 激活第一個 subplot plt.subplot(2, 1, 1) # 繪制第一個圖像 plt.plot(x, y_sin) plt.title('Sine') # 將第二個 subplot 激活,並繪制第二個圖像 plt.subplot(2, 1, 2) plt.plot(x, y_cos) plt.title('Cosine') # 展示圖像 plt.show()
上面的代碼應該產生以下輸出:
bar()
pyplot子模塊提供bar()函數來生成條形圖。 以下示例生成兩組x和y數組的條形圖。
示例
from matplotlib import pyplot as plt x = [5,8,10] y = [12,16,6] x2 = [6,9,11] y2 = [6,15,7] plt.bar(x, y, align = 'center') plt.bar(x2, y2, color = 'g', align = 'center') plt.title('Bar graph') plt.ylabel('Y axis') plt.xlabel('X axis') plt.show()
NumPy - 使用 Matplotlib 繪制直方圖
NumPy 有一個numpy.histogram()函數,它是數據的頻率分布的圖形表示。 水平尺寸相等的矩形對應於類間隔,稱為bin,變量height對應於頻率。
numpy.histogram()
numpy.histogram()函數將輸入數組和bin作為兩個參數。 bin數組中的連續元素用作每個bin的邊界。
import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) ] np.histogram(a,bins = [0,20,40,60,80,100]) hist,bins = np.histogram(a,bins = [0,20,40,60,80,100]) print hist print bins
輸出如下:
[3 4 5 2 1]
[0 20 40 60 80 100]
plt()
Matplotlib 可以將直方圖的數字表示轉換為圖形。 pyplot子模塊的plt()函數將包含數據和bin數組的數組作為參數,並轉換為直方圖。
from matplotlib import pyplot as plt import numpy as np a = np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27]) plt.hist(a, bins = [0,20,40,60,80,100]) plt.title("histogram") plt.show()
輸出如下:
NumPy - IO
ndarray對象可以保存到磁盤文件並從磁盤文件加載。 可用的 IO 功能有:
-
load()和save()函數處理 numPy 二進制文件(帶npy擴展名) -
loadtxt()和savetxt()函數處理正常的文本文件
NumPy 為ndarray對象引入了一個簡單的文件格式。 這個npy文件在磁盤文件中,存儲重建ndarray所需的數據、圖形、dtype和其他信息,以便正確獲取數組,即使該文件在具有不同架構的另一台機器上。
numpy.save()
numpy.save()文件將輸入數組存儲在具有npy擴展名的磁盤文件中。
import numpy as np a = np.array([1,2,3,4,5]) np.save('outfile',a)
為了從outfile.npy重建數組,請使用load()函數。
import numpy as np b = np.load('outfile.npy') print b
輸出如下:
array([1, 2, 3, 4, 5])
save()和load()函數接受一個附加的布爾參數allow_pickles。 Python 中的pickle用於在保存到磁盤文件或從磁盤文件讀取之前,對對象進行序列化和反序列化。
savetxt()
以簡單文本文件格式存儲和獲取數組數據,是通過savetxt()和loadtx()函數完成的。
示例
import numpy as np a = np.array([1,2,3,4,5]) np.savetxt('out.txt',a) b = np.loadtxt('out.txt') print b
輸出如下:
[ 1. 2. 3. 4. 5.]
savetxt()和loadtxt()數接受附加的可選參數,例如頁首,頁尾和分隔符。
NumPy - 實用資源
以下資源包含有關 NumPy 的其他信息。 請使用它們獲得更多的深入知識。
轉載鏈接:https://www.jianshu.com/p/57e3c0a92f3a
