numpy學習

文章目錄

NumPy

numpy 是python語言的一個擴展程序庫, 支持大量的維度數組與矩陣運算, 此外也針對數組提供大量的數學函數庫.

numpy是一個運行速度非常快的數學庫, 主要用於數組計算, 包含:

一個強大的N維數組對象ndarry
廣播功能函數
整合C/C++/Fortran代碼的工具
線性代數, 傅里葉變換, 隨機數生成等功能

numpy應用

numpy與scipy(Scientific Python)和 Matplotlib(繪圖庫)一起使用, 這種組合廣泛用於替代 MatLab,是一個強大的科學計算環境,有助於我們通過 Python 學習數據科學或者機器學習。

SciPy 是一個開源的 Python 算法庫和數學工具包。

SciPy 包含的模塊有最優化、線性代數、積分、插值、特殊函數、快速傅里葉變換、信號處理和圖像處理、常微分方程求解和其他科學與工程中常用的計算。

Matplotlib 是 Python 編程語言及其數值數學擴展包 NumPy 的可視化操作界面。它爲利用通用的圖形用戶界面工具包,如 Tkinter, wxPython, Qt 或 GTK+ 嚮應用程序嵌入式繪圖提供了應用程序接口(API)。

numpy 安裝

  1. 使用已經集成了這些模塊的開發工具如Anaconda, Enthought Canopy, Python(x,y), WinPython, Pyzo

  2. 使用pip來安裝

    python -m pip install --user numpy scipy matplotlib ipython jupyter pandas sympy nose
    

    –user 選項可以設置只安裝在當前的用戶下, 而不是寫入到系統目錄

linux下安裝

ubuntu&debian

sudo apt-get install python-numpy python-scipy python-matplotlib ipython ipython-notebook python-pandas python-sympy python-nose

centos& Fedora

sudo dnf install numpy scipy python-matplotlib ipython python-pandas sympy python-nose atlas-devel

mac:

python -m pip install numpy scipy matplotlib

安裝驗證

>>> from nummpy import *
>>> eye(4)
array([[ 1.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.],
       [ 0.,  0.,  0.,  1.]])

eye(4)生成對角矩陣

numpy Ndarray 對象

NumPy 最重要的一個特點是其 N 維數組對象 ndarray,它是一系列同類型數據的集合,以 0 下標爲開始進行集合中元素的索引。

ndarray 對象是用於存放同類型元素的多維數組。

ndarray 中的每個元素在內存中都有相同存儲大小的區域。

ndarray 內部由以下內容組成:

1.一個指向數據(內存或內存映射文件中的一塊數據)的指針
2.數據類型或dtype, 描述在數組中的固定大小值的格子
3.一個表示數組形狀(shape)的元組, 表示各維度大小的元組
4.一個跨度元組(stride), 其中的整數指的是爲了前進到當前維度下一個元素需要"跨過"的字節數.

ndarray內部結構:

內部結構

跨度可以是負數, 這樣會使數組在內存中向後移動, 切片中obj[::-1]obj[:,::-1]就是如此.

創建一個ndarray只需要調用Numpy的array函數即可:

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
名稱 描述
object 數組或嵌套的數列
dtype 數組元素的數據類型, 可選
copy 對象是否需要複製, 可選
order 創建數組的樣式, C爲行方向, F爲列方向, A爲任意方向(默認)
subok 默認返回一個與基類類型一致的數組
ndmin 指生成數的最小維度

實例

import numpy

a = numpy.array([1,2,3])
print (a)

輸出:
[1 2 3]

實例2:

# 多於一個維度, 兩個數組
import numpy

a = numpy.array([[1,2,3], [4,5]])
print (a)
[[1, 2, 3] [4, 5]]
[Finished in 0.1s]

實例3:

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

輸出:
[[1 2 3 4 5]]
[Finished in 0.1s]

實例4:

# dtype 參數
import numpy
a = numpy.array([1,2,3,4,5], dtype = complex)
print (a)

輸出:

[ 1.+0.j  2.+0.j  3.+0.j  4.+0.j  5.+0.j]
[Finished in 0.1s]

ndarray對象由計算機內存的連續一維部分組成, 並結合索引模式, 將每個元素映射到內存塊中的一個位置. 內存塊一行順序(C樣式)或列順序(FORTRAN或Matlab風格, 即F樣式)來保存元素

numpy數據類型

numpy支持的數據類型比python內置的類型要多很多, 基本上可以和C語言的數據類型對應上, 其中部分類型對應爲Python內置的類型.

常用基本類型:

名稱 描述
bool_ 布爾型數據類型(True 或者 False)
int_ 默認的整數類型(類似於 C 語言中的 long,int32 或 int64)
intc 與 C 的 int 類型一樣,一般是 int32 或 int 64
intp 用於索引的整數類型(類似於 C 的 ssize_t,一般情況下仍然是 int32 或 int64)
int8 字節(-128 to 127)
int16 整數(-32768 to 32767)
int32 整數(-2147483648 to 2147483647)
int64 整數(-9223372036854775808 to 9223372036854775807)
uint8 無符號整數(0 to 255)
uint16 無符號整數(0 to 65535)
uint32 無符號整數(0 to 4294967295)
uint64 無符號整數(0 to 18446744073709551615)
float_ float64 類型的簡寫
float16 半精度浮點數,包括:1 個符號位,5 個指數位,10 個尾數位
float32 單精度浮點數,包括:1 個符號位,8 個指數位,23 個尾數位
float64 雙精度浮點數,包括:1 個符號位,11 個指數位,52 個尾數位
complex_ complex128 類型的簡寫,即 128 位複數
complex64 複數,表示雙 32 位浮點數(實數部分和虛數部分)
complex128 複數,表示雙 64 位浮點數(實數部分和虛數部分)

numpy的數值類型實際上是dtype對象的實例, 並對應唯一的字符, 包括np.bool_. np.int32, np.float32 , 等等

數據類型對象(dtype)

數據類型對象是用來描述與數組對應的內存區域如何使用, 這依賴如下幾個方面:

  • 數據類型(整數, 浮點數或者python對象)
  • 數據的大小(列如, 整數使用多少個字節存儲)
  • 數據的字節順序(小端法或大端法)
  • 在結構化類型的情況下, 字段的名稱, 每個字段的數據類型和每個字段所取的內存塊的部分
  • 如果數據 類型是子數組, 他的形狀和數據類型

字節順序是通過對數據類型預先設定"<“或”>"來決定的. "<"意味着小端法(最小值存儲在最小的地址, 即低位組放在最前面). ">"意味着大端法(最重要的字節存儲在最小的地址, 即高位組放在最前面).

dtype對象是使用以下語法構造的:

numpy.dtype(object, align, copy)

object: 要轉換爲的數據類型對象

align: 如果爲true, 填充字段使其類似C的結構體

copy: 複製dtype對象, 如果爲false, 則是對內置數據類型對象的引用

實例

import numpy
# 使用標量類型
a = numpy.dtype(numpy.int32)
print (a)

輸出:

int32
[Finished in 0.1s]

實例2:

# int8, int16, int32, int64 四種數據類型可以使用字符串 'i1', 'i2','i4','i8' 代替
import numpy
a = numpy.dtype('i4')
print (a)

輸出:

int32
[Finished in 0.1s]

實例3:

import numpy
# 字節順序標註
a = numpy.dtype('<i4')
print (a)

輸出:
    int32

結構化數據類型的使用, 類型字段和對應的實際類型將被創建.

實例4:

import numpy
a = numpy.dtype([('age', numpy.int8)])
print (a)
[('age', 'i1')]
[Finished in 0.1s]

實例5:

import numpy
# 數據類型應用到ndarray對象
dt = numpy.dtype([('age', numpy.int8)])
a = numpy.array([(10,),(20,),(30,)], dtype = dt)
print (a)
[(10,) (20,) (30,)]
[Finished in 0.1s]

實例6:

# 類型字段名可以用於存取實際的age列
import numpy
dt = numpy.dtype([('age', numpy.int8)])
a = numpy.array([(10,),(20,),(30,)], dtype = dt)
print (a['age'])
[10 20 30]
[Finished in 0.1s]

下面的示例定義一個結構化數據類型 student,包含字符串字段 name,整數字段 age,及浮點字段 marks,並將這個 dtype 應用到 ndarray 對象

實例7:

import numpy
student = numpy.dtype([('name','S20'),('age','i1'),('marks','f4')])
print (student)
[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')]
[Finished in 0.1s]

實例8:

import numpy
student = numpy.dtype([('name','S20'),('age','i1'),('marks','f4')])
a = numpy.array([('abc', 21,50),('xyz', 18, 75)], dtype = student)
print (a)
[(b'abc', 21,  50.) (b'xyz', 18,  75.)]
[Finished in 0.1s]

dtype相當於提前定義的一張數據表裏面各個字段的 名字 數據類型, numpy.array()按照提前定義的字段, 依次填入進去. 注意python2和3的區別.

每個內建類型都已一個唯一定義它的字符代碼如下:

字符 對應類型
b 布爾型
i (有符號) 整型
u 無符號整型 integer
f 浮點型
c 複數浮點型
m timedelta(時間間隔)
M datetime(日期時間)
O (Python) 對象
S, a (byte-)字符串
U Unicode
V 原始數據 (void)

numpy數組屬性

NumPy 數組的維數稱爲秩(rank),秩就是軸的數量,即數組的維度,一維數組的秩爲 1,二維數組的秩爲 2,以此類推。

在 NumPy中,每一個線性的數組稱爲是一個軸(axis),也就是維度(dimensions)。比如說,二維數組相當於是兩個一維數組,其中第一個一維數組中每個元素又是一個一維數組。所以一維數組就是 NumPy 中的軸(axis),第一個軸相當於是底層數組,第二個軸是底層數組裏的數組。而軸的數量——秩,就是數組的維數。

很多時候可以聲明 axis。axis=0,表示沿着第 0 軸進行操作,即對每一列進行操作;axis=1,表示沿着第1軸進行操作,即對每一行進行操作。

NumPy 的數組中比較重要 ndarray 對象屬性有:

屬性 說明
ndarray.ndim 秩,即軸的數量或維度的數量
ndarray.shape 數組的維度,對於矩陣,n 行 m 列
ndarray.size 數組元素的總個數,相當於 .shape 中 n*m 的值
ndarray.dtype ndarray 對象的元素類型
ndarray.itemsize ndarray 對象中每個元素的大小,以字節爲單位
ndarray.flags ndarray 對象的內存信息
ndarray.real ndarray元素的實部
ndarray.imag ndarray 元素的虛部
ndarray.data 包含實際數組元素的緩衝區,由於一般通過數組的索引獲取元素,所以通常不需要使用這個屬性。

ndarray.ndim

返回數組的維數等於秩

import numpy
a = numpy.arange(24)
print (a.ndim) # a現只有一個維度 
# 現在調整其大小
b = a.reshape(2,4,3) # b現在擁有3個維度
print (b.ndim)
1
3

ndarray.shape

ndarray.shape 表示數組的維度,返回一個元組,這個元組的長度就是維度的數目,即 ndim 屬性(秩)。比如,一個二維數組,其維度表示"行數"和"列數"。

ndarray.shape 也可以用於調整數組大小。

實例:
import numpy 
a = numpy.array([[1,2,3],[4,5,6]])
print (a.shape) # 二行三列

(2, 3)
[Finished in 0.1s]

調整大小:

import numpy 
a = numpy.array([[1,2,3],[4,5,6]])
a.shape = (3,2) # 三行二列
print (a)
[[1 2]
 [3 4]
 [5 6]]
[Finished in 0.1s]

numpy也提供了reshape函數來調整數組大小.

import numpy
a  = numpy.array([[1,2,3],[4,5,6]])
b  = a.reshape(3,2)
print (b)
[[1 2]
 [3 4]
 [5 6]]
[Finished in 0.3s]

ndarray.itemsize

ndarray.itemsize 以字節的形式返回數組中每一個元素的大小。

例如,一個元素類型爲 float64 的數組 itemsiz 屬性值爲 8(float64 佔用 64 個 bits,每個字節長度爲 8,所以 64/8,佔用 8 個字節),又如,一個元素類型爲 complex32 的數組 item 屬性爲 4(32/8)。

實例:

import numpy
# 數組的dtype爲int8(一個字節)
a = numpy.array([1,99,2,3,4,5], dtype = numpy.int8)
print (a.itemsize)

# 數組的dtype現在爲float64(8個字節)
b = numpy.array([1,2,3,4,5], dtype = numpy.float64)
print (b.itemsize)

1
8

ndarray.flags

ndarray.flags 返回ndarray對象的內存信息, 包含以下屬性.

屬性 描述
C_CONTIGUOUS © 數據是在一個單一的C風格的連續段中
F_CONTIGUOUS (F) 數據是在一個單一的Fortran風格的連續段中
OWNDATA (O) 數組擁有它所使用的內存或從另一個對象中借用它
WRITEABLE (W) 數據區域可以被寫入,將該值設置爲 False,則數據爲只讀
ALIGNED (A) 數據和所有元素都適當地對齊到硬件上
UPDATEIFCOPY (U) 這個數組是其它數組的一個副本,當這個數組被釋放時,原數組的內容將被更新
import numpy
a = numpy.array([1,2,33])
print (a.flags)
  C_CONTIGUOUS : True
  F_CONTIGUOUS : True
  OWNDATA : True
  WRITEABLE : True
  ALIGNED : True
  UPDATEIFCOPY : False
[Finished in 0.1s]

numpy創建數組

ndarray數組除了可以使用底層ndarray構造器來創建外, 也可以通過以下幾種方式來創建.

numpy.empty

numpy.empty 方法用來創建一個指定形狀(shape), 數據類型(dtype)且未初始化的數組:

numpy.empty(shape, dtype = float, order = 'C')
參數 描述
shape 數組形狀
dtype 數據類型,可選
order 有"C"和"F"兩個選項,分別代表,行優先和列優先,在計算機內存中的存儲元素的順序。
import numpy
a = numpy.empty([3,2], dtype = int)
print (a)

[[    140605049899912     140605049899912]
 [    140605009638320     140605009626224]
 [7205759936368964608   72483105062780931]]
[Finished in 0.1s]

數組元素爲隨機值, 因爲他們還未初始化

numpy.zeros

創建指定大小的數組, 數組元素以0 來填充.

numpy.zeros(shape, dtype = float, order = 'C')

參數說明:

參數 描述
shape 數組形狀
dtype 數據類型,可選
order ‘C’ 用於 C 的行數組,或者 ‘F’ 用於 FORTRAN 的列數組
import numpy

# 默認爲浮點數
a  = numpy.zeros(5)
print (a)

# 設置類型爲整數
b  = numpy.zeros((5,),dtype = numpy.int)
print (b)

# 自定義類型
c = numpy.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
print (c)

[ 0.  0.  0.  0.  0.]
[0 0 0 0 0]
[[(0, 0) (0, 0)]
 [(0, 0) (0, 0)]]
[Finished in 0.1s]

numpy.ones

創建指定形狀的數組, 數組元素以1來填充:

numpy.ones(shape, dtype = None, order = 'C')

參數解釋:

參數 描述
shape 數組形狀
dtype 數據類型,可選
order ‘C’ 用於 C 的行數組,或者 ‘F’ 用於 FORTRAN 的列數組

實例:

import numpy
# 默認爲浮點數
a = numpy.ones(5)
print (a)
# 自定義類型
b = numpy.ones([3,3], dtype = [('x', int),('y', float)])
print (b)
[ 1.  1.  1.  1.  1.]
[[(1,  1.) (1,  1.) (1,  1.)]
 [(1,  1.) (1,  1.) (1,  1.)]
 [(1,  1.) (1,  1.) (1,  1.)]]
[Finished in 0.1s]

從已有數組創建數組

numpy.asarray

numpy.asarray 類似 numpy.array, 但 numpy.asarray 參數有三個, 比numpy.array少兩個

numpy.asarray(a, dtype = None, order = None)

參數說明:

參數 描述
a 任意形式的輸入參數,可以是,列表, 列表的元組, 元組, 元組的元組, 元組的列表,多維數組
dtype 數據類型,可選
order 可選,有"C"和"F"兩個選項,分別代表,行優先和列優先,在計算機內存中的存儲元素的順序。

實例:

列表裝換爲ndarray:

import numpy
x  = [1,2,3]
a = numpy.asarray(x)
print (a)


[1 2 3]
[Finished in 0.1s]

元組轉換爲ndarray:

import numpy
x  = (1,2,3)
a = numpy.asarray(x)
print (a)

[1 2 3]

元組列表轉換爲ndarray:

import numpy
x  = [(1,2,3),(4,5)]
a = numpy.asarray(x)
print (a)

[(1, 2, 3) (4, 5)]
[Finished in 0.1s]

加上dtype參數:

import numpy
x  = [1,2,3,4,5]
a = numpy.asarray(x, dtype = float)
print (a)

[ 1.  2.  3.  4.  5.]
[Finished in 0.1s]

numpy.frombuffer

numpy.frombuffer 用於實現動態數組, numpy.frombuffer接受buffer輸入參數, 以流的形式讀入轉化成ndarray對象.

numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

注: buffer是字符串的時候, python3 默認str是unicode類型, 所以要轉換成bytestring在原str前加上b

參數說明:

參數 描述
buffer 可以是任意對象,會以流的形式讀入。
dtype 返回數組的數據類型,可選
count 讀取的數據數量,默認爲-1,讀取所有數據。
offset 讀取的起始位置,默認爲0。

python3:

import numpy
s = b'hello word'
a = numpy.frombuffer(s, dtype = 'S1')
print (a)

[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'd']
[Finished in 0.1s]

python2:

import numpy

s = 'hello word'
a = numpy.frombuffer(s, dtype = 'S1')
print (a)


pig@deep:~/Desktop/note/python/numpy$ python test.py 
['h' 'e' 'l' 'l' 'o' ' ' 'w' 'o' 'r' 'd']

numpy.fromiter

numpy.fromiter 方法從可迭代對象中建立ndarray 對象, 返回一維數組

numpy.fromiter(iterable, dtype, count = -1)
參數 描述
iterable 可迭代對象
dtype 返回數組的數據類型
count 讀取的數據數量,默認爲-1,讀取所有數據
import numpy
# 使用range函數創建列表對象
list = range(5)
it = iter(list)
# 使用迭代器創建 ndarray
a = numpy.fromiter(it, dtype = float)
print (a)

[ 0.  1.  2.  3.  4.]
[Finished in 0.1s]

numpy從數值範圍創建數組

numpy.arange

numpy 包中的使用arange函數創建數值範圍並返回ndarray對象, 函數格式如下:

numpy.arange(start, stop, step, dtype)

根據start與stop指定的範圍以及step設定的步長, 生成一個ndarray

參數說明:

參數 描述
start 起始值,默認爲0
stop 終止值(不包含)
step 步長,默認爲1
dtype 返回ndarray的數據類型,如果沒有提供,則會使用輸入數據的類型。

實例:

生成0-5的數組

import numpy
a = numpy.arange(5, dtype = float)
print (a)


[ 0.  1.  2.  3.  4.]
[Finished in 0.1s]

設置起始值, 終止值及步長:

import numpy
a = numpy.arange(10,20,2, dtype = float)
print (a)

[ 10.  12.  14.  16.  18.]
[Finished in 0.1s]

numpy.linspace

numpy.linspace函數用於創建一個一維數組, 數組是一個等差數列構成的, 格式如下:

numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

參數說明:

參數 描述
start 序列的起始值
stop 序列的終止值,如果endpointtrue,該值包含於數列中
num 要生成的等步長的樣本數量,默認爲50
endpoint 該值爲 true 時,數列中中包含stop值,反之不包含,默認是True。
retstep 如果爲 True 時,生成的數組中會顯示間距,反之不顯示。
dtype ndarray 的數據類型

實例:

設置起始點爲1, 終止點爲10, 數列個數爲10

import numpy
a = numpy.linspace(1,10,10, dtype = float)
print (a)

[  1.   2.   3.   4.   5.   6.   7.   8.   9.  10.]
[Finished in 0.1s]

設置元素爲1的等差數列:

import numpy
a = numpy.linspace(1,1,10, dtype = float)
print (a)

[ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
[Finished in 0.1s]

將endpoint設爲false, 不包含終止值;

import numpy
a = numpy.linspace(10,20,5,endpoint = False, dtype = float)
print (a)


[ 10.  12.  14.  16.  18.]
[Finished in 0.1s]

如果將endpoint 設爲true, 則會包含20.

以下實例設置間距:

import numpy
a = numpy.linspace(1,10,10,retstep = True)
print (a)
# 拓展列子
b = numpy.linspace(1,10,10).reshape([10,1])
print (b)
(array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.]), 1.0)
[[  1.]
 [  2.]
 [  3.]
 [  4.]
 [  5.]
 [  6.]
 [  7.]
 [  8.]
 [  9.]
 [ 10.]]
[Finished in 0.1s]

numpy.logspace

numpy.logspace函數用於創建一個等比數列格式如下:

numpy.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)

base參數意思是取對數的時候log的下標

參數 描述
start 序列的起始值爲:base ** start
stop 序列的終止值爲:base ** stop。如果endpointtrue,該值包含於數列中
num 要生成的等步長的樣本數量,默認爲50
endpoint 該值爲 true 時,數列中中包含stop值,反之不包含,默認是True。
base 對數 log 的底數。
dtype ndarray 的數據類型
import numpy
# 默認底數是10
a = numpy.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.        ]
[Finished in 0.1s]
import numpy
# 底數是2
a = numpy.logspace(0, 9,10, base=2)
print (a)


[   1.    2.    4.    8.   16.   32.   64.  128.  256.  512.]
[Finished in 0.1s]

numpy切片和索引

ndarray對象的內容可以通過索引或切片來訪問和修改,與 Python 中 list 的切片操作一樣。

ndarray 數組可以基於 0 - n 的下標進行索引,切片對象可以通過內置的 slice 函數,並設置 start, stop 及 step 參數進行,從原數組中切割出一個新數組。

>>> import numpy
>>> a = numpy.arange(10)
>>> s = slice(2,7,2) # 從索引2 開始索引到7停止, 間隔爲2
>>> print (a[s])
[2 4 6]

通過arange()函數創建ndarray對象, 然後, 分別設置起始, 終止和步長的參數爲2, 7 和2.

也可以通過冒號分割切片參數start:stop:step來進行切片操作:

>>> import numpy
>>> a = numpy.arange(10)
>>> b = a[2:7:2]
>>> print (b)
[2 4 6]
>>> 

索引和list中的索引差不多 單個參數[2] , [2:]索引開始後面的所有項都將提取,如果[2:7] 則提取兩個索引之間的項(不包括停止索引)

多維數組同樣適用上述索引提取方法:

>>> import numpy
>>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
>>> print (a)
[[1 2 3]
 [4 5 6]
 [7 8 9]]
>>> print (a[1:])
[[4 5 6]
 [7 8 9]]
>>> 

切片還可以包括省略號...來使選擇元組的長度與數組的維度相同, 如果在行位置使用省略號, 他將返回包含行中元素的ndarray

>>> import numpy
>>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
>>> print (a[...,1]) # 第二列元素
[2 5 8]
>>> print (a[1,...]) # 第二行元素
[4 5 6]
>>> print (a[...,1:]) # 第二例及剩下的所有元素
[[2 3]
 [5 6]
 [8 9]]
>>> 

numpy 高級索引

NumPy 比一般的 Python 序列提供更多的索引方式。除了之前看到的用整數和切片的索引外,數組可以由整數數組索引、布爾索引及花式索引。

整數數組索引

以下實例獲取數組中(0,0),(1,1)和(2,0)位置處的元素。

import numpy
x = numpy.array([[1,2],[3,4],[5,6]])
y = x[[0,1,2], [0,1,0]]
print (y)


[1 4 5]
[Finished in 0.1s]
區別:
import numpy
x = numpy.array([[1,2],[3,4],[5,6]])
y = x[[0,1], [0,1]]
print (y)
print (x)

[1 4]
[[1 2]
 [3 4]
 [5 6]]
[Finished in 0.1s]

獲取4x3數組中的四個角元素, 行索引爲[0,0]和[3,3] 而列索引爲[0,2]和[0,2]

import numpy
x = numpy.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]])
print ('數組:')
print (x)
print ('\n')
rows = numpy.array([[0,0],[3,3]])
cols = numpy.array([[0,2],[0,2]])
y = x[rows, cols]
print ('角上的四個元素:')
print (y)

座標爲00 02 30 32
數組:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]


角上的四個元素:
[[ 0  2]
 [ 9 11]]
[Finished in 0.1s]

返回結果是包含每個角元素的ndarray對象

可以藉助切片:...與索引數組組合

import numpy
a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
b = a[1:3,1:3]
c = a[1:3,[1,2]]
d = a[...,1:]
print (a)
print (b)
print (c)
print (d)

[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[5 6]
 [8 9]]
[[5 6]
 [8 9]]
[[2 3]
 [5 6]
 [8 9]]
[Finished in 0.1s]

要獲取元素 的行索引集合, 列索引集合來獲取元素, 如果是獲取某個區域的元素, 則使用:

布爾索引

我們可以通過一個布爾數組來索引目標數組。

布爾索引通過布爾運算(如:比較運算符)來獲取符合指定條件的元素的數組。

以下實例獲取大於 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]
[Finished in 0.3s]

以下使用~(取補運算符) 來過濾NaN

import numpy 
a = numpy.array([numpy.nan, 1, 2, numpy.nan, 3, 4, 5])
print (a[~numpy.isnan(a)])

[ 1.  2.  3.  4.  5.]
[Finished in 0.1s]

從數組中過濾掉非複數元素:

import numpy 
a = numpy.array([1, 2+6j,5,3.5])
print (a[numpy.iscomplex(a)])

[ 2.+6.j]
[Finished in 0.1s]

花式索引

花式索引指的是利用整數數組進行索引。

花式索引根據索引數組的值作爲目標數組的某個軸的下標來取值。對於使用一維整型數組作爲索引,如果目標是一維數組,那麼索引的結果就是對應位置的元素;如果目標是二維數組,那麼就是對應下標的行。

花式索引跟切片不一樣,它總是將數據複製到新數組中。

  1. 傳入順序索引數組

    import numpy 
    a = numpy.arange(32)
    x = a.reshape((8,4))
    print (a)
    print (x)
    print (x[[4,2,1,7]])
    
    
    [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
     25 26 27 28 29 30 31]
    [[ 0  1  2  3]
     [ 4  5  6  7]
     [ 8  9 10 11]
     [12 13 14 15]
     [16 17 18 19]
     [20 21 22 23]
     [24 25 26 27]
     [28 29 30 31]]
    [[16 17 18 19]
     [ 8  9 10 11]
     [ 4  5  6  7]
     [28 29 30 31]]
    [Finished in 0.1s]
    
  2. 傳入倒敘索引數組

import numpy 
a = numpy.arange(32)
x = a.reshape((8,4))
print (a)
print (x)
print (x[[-4,-2,-1,-7]])


[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 25 26 27 28 29 30 31]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]
 [24 25 26 27]
 [28 29 30 31]]
[[16 17 18 19]
 [24 25 26 27]
 [28 29 30 31]
 [ 4  5  6  7]]
[Finished in 0.1s]
  1. 傳入多個索引數組(要使用np.ix_)
import numpy 
a = numpy.arange(32)
x = a.reshape((8,4))
print (x)
print (x[numpy.ix_([1,5,7,2],[0,3,1,2])])

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]
 [24 25 26 27]
 [28 29 30 31]]
[[ 4  7  5  6]
 [20 23 21 22]
 [28 31 29 30]
 [ 8 11  9 10]]
[Finished in 0.1s]

行索引配合列索引

numpy廣播(broadcast)

廣播(Broadcast)是 numpy 對不同形狀(shape)的數組進行數值計算的方式, 對數組的算術運算通常在相應的元素上進行。

如果兩個數組 a 和 b 形狀相同,即滿足 a.shape == b.shape,那麼 a*b 的結果就是 a 與 b 數組對應位相乘。這要求維數相同,且各維度的長度相同。

[1,2,3,4] * [10,20,30,40]

import numpy 
a = numpy.array([1,2,3,4])
b = numpy.array([10,20,30,40])
c = a * b
print (c)

[ 10  40  90 160]
[Finished in 0.1s]

當運算中的兩個數組形狀不同時, numpy將自動觸發廣播機制.:

import numpy 
a  = numpy.array([[0,0,0],
	[10,10,10],
	[20,20,20],
	[30,30,30]])
b = numpy.array([1,2,3])
print (a + b)

[[ 1  2  3]
 [11 12 13]
 [21 22 23]
 [31 32 33]]
[Finished in 0.1s]

廣播的規則:

  • 讓所有輸入數組都向其中形狀最長的數組看齊,形狀中不足的部分都通過在前面加 1 補齊。
  • 輸出數組的形狀是輸入數組形狀的各個維度上的最大值。
  • 如果輸入數組的某個維度和輸出數組的對應維度的長度相同或者其長度爲 1 時,這個數組能夠用來計算,否則出錯。
  • 當輸入數組的某個維度的長度爲 1 時,沿着此維度運算時都用此維度上的第一組值。

**簡單理解:**對兩個數組,分別比較他們的每一個維度(若其中一個數組沒有當前維度則忽略),滿足:

  • 數組擁有相同形狀。
  • 當前維度的值相等。
  • 當前維度的值有一個是 1。

若條件不滿足,拋出 “ValueError: frames are not aligned” 異常。

tile()函數就是將原矩陣橫向, 縱向的複製.

tile(mat, (1,4)) 複製爲原來的四倍

numpy 迭代數組

NumPy 迭代器對象 numpy.nditer 提供了一種靈活訪問一個或者多個數組元素的方式。

迭代器最基本的任務的可以完成對數組元素的訪問。

接下來我們使用 arange() 函數創建一個 2X3 數組,並使用 nditer 對它進行迭代。

import numpy as np 
a = np.arange(6).reshape(2,3)
print ('原數組:')
print (a)
print ('\n')
for x in np.nditer(a):
	print (x, end=', ')
print ('\n')

原數組:
[[0 1 2]
 [3 4 5]]


0, 1, 2, 3, 4, 5, 

[Finished in 0.1s]

以上實例不是使用標準 C 或者 Fortran 順序,選擇的順序是和數組內存佈局一致的,這樣做是爲了提升訪問的效率,默認是行序優先(row-major order,或者說是 C-order)。

這反映了默認情況下只需訪問每個元素,而無需考慮其特定順序。我們可以通過迭代上述數組的轉置來看到這一點,並與以 C 順序訪問數組轉置的 copy 方式做對比,如下實例:

import numpy as np 
a = np.arange(6).reshape(2,3)
for x in np.nditer(a.T):
	print (x, end=', ')
print ('\n')

for x in np.nditer(a.T.copy(order='C')):
	print (x, end=', ')
print ('\n')


0, 1, 2, 3, 4, 5, 

0, 3, 1, 4, 2, 5, 

[Finished in 0.1s]

從上述例子可以看出,a 和 a.T 的遍歷順序是一樣的,也就是他們在內存中的存儲順序也是一樣的,但是 a.T.copy(order = ‘C’) 的遍歷結果是不同的,那是因爲它和前兩種的存儲方式是不一樣的,默認是按行訪問。

控制便來順序

  • for x in np.nditer(a, order="F"):Fortran order, 列優先
  • for x in np.nditer(a.T, order='C'): C order , 行優先
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, end=", ")
print ('\n')
print ('-----F-------')
c = b.copy(order='F')
print (c)
for x in np.nditer(c):
	print (x, end=', ')
原數組:
[[ 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, [Finished in 0.1s]

b=a.T表示數組的轉置, 默認情況下nditer是以行來讀取的, 當然也可以直接以列來讀取, 使用nditer指定order以什麼方式讀取如下:

import numpy as np 
a = np.arange(0,60,5)
a = a.reshape(3,4)
print (str('原').center(15,'*'))
print (a)
print ('\n')
print (str('C').center(15,'*'))
for x in np.nditer(a, order = 'C'):
	print (x, end = ', ')
print ('\n')
print ('F'.center(15, '*'))
for x in np.nditer(a, order = 'F'):
	print (x, end = ', ')
*******原*******
[[ 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, [Finished in 0.1s]

修改數組中元素的值

nditer 對象有另一個可選參數op_flags 默認情況下, nditer將視待迭代遍歷的數組爲只讀對象(read-only), 爲了在遍歷數組的同時, 實現對數組元素值得修改, 必須指定read-write 或者 write-only 的模式.

import numpy
a = numpy.arange(0,60,5)
a = a.reshape(3,4)
print ('原始數組'.center(15,'*'))
print (a)
print ('\n')
for x in numpy.nditer(a, op_flags=['readwrite']):
	x[...]=2*x
print ('修改後'.center(15,'*'))
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]]
[Finished in 0.1s]

使用外部循環:

nditer 類的構造器擁有flags參數, 他可以接受下列值:

參數 描述
c_index 可以跟蹤 C 順序的索引
f_index 可以跟蹤 Fortran 順序的索引
multi-index 每次迭代可以跟蹤一種索引類型
external_loop 給出的值是具有多個值的一維數組,而不是零維數組
import numpy
a = numpy.arange(0,60,5)
a = a.reshape(3,4)
print ('原始數組'.center(20,'*'))
print (a)
print ('\n')
print ('修改後的數組:'.center(20,'*'))
for x in numpy.nditer(a, flags = ['external_loop'], order = 'F'):
	print (x, end=", ")
********原始數組********
[[ 0  5 10 15]
 [20 25 30 35]
 [40 45 50 55]]


******修改後的數組:*******
[ 0 20 40], [ 5 25 45], [10 30 50], [15 35 55], [Finished in 0.1s]

廣播迭代

如果兩個數組是可廣播的, nditer組合對象能夠同時迭代他們, 假設數組a的維度爲3x4, 數組b的維度爲1x4 則使用以下迭代器(數組b被廣播到a的大小)

import numpy
a = numpy.arange(0,60,5)
a = a.reshape(3,4)
print ('第一個數組'.center(20, "*"))
print (a)
print ('\n')
print ('第二個數組'.center(20, "*"))
b = numpy.array([1,2,3,4],dtype = int)
print (b)
print ('\n')
print ('修改之後的數組'.center(20, "*"))
for x,y in numpy.nditer([a,b]):
	print ('%d:%d' % (x, y), end=', ')
	
	
*******第一個數組********
[[ 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, [Finished in 0.1s]

數組操作

處理數組大概分爲以下幾類:

  • 修改數組形狀
  • 翻轉數組
  • 修改數組 維度
  • 連接數組
  • 分割數組
  • 數組元素的添加與刪除

修改數組形狀

函數 描述
reshape 不改變數據的條件下修改形狀
flat 數組元素迭代器
flatten 返回一份數組拷貝,對拷貝所做的修改不會影響原始數組
ravel 返回展開數組
numpy.reshape

numpy.reshape 函數可以在不改變數據的條件下修改形狀,格式如下: numpy.reshape(arr, newshape, order=‘C’)

  • arr:要修改形狀的數組
  • newshape:整數或者整數數組,新的形狀應當兼容原有形狀
  • order:‘C’ – 按行,‘F’ – 按列,‘A’ – 原順序,‘k’ – 元素在內存中的出現順序。
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

numpy.ndarray.flat 是一個數組元素迭代器, 實例:

import numpy
a = numpy.arange(9).reshape(3,3)
print ('原數組'.center(20,'*'))
for row in a:
	print (row)
# 對數組中每個元素都進行處理, 可以使用flat屬性, 該屬性是一個數組元素迭代器.
print ('迭代後的數組'.center(20, '*'))
for element in a.flat:
	print (element)
	
	
********原數組*********
[0 1 2]
[3 4 5]
[6 7 8]
*******迭代後的數組*******
0
1
2
3
4
5
6
7
8
[Finished in 0.3s]
numpy.ndarray.flatten

numpy.ndarray.flatten 返回一份數組拷貝, 對拷貝所做的修改不會影響原始數組, 格式:

ndarray.flatten(order='C')

order‘C’–按行, ‘F’-- 按列, ‘A’ – 按原順序, ‘K’ – 元素在內存中的出現順序.

import numpy
a = numpy.arange(8).reshape(2,4)
print('原'.center(20, '*'))
print (a)
print ('\n')
print ('展開數組:'.center(20, '*'))
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]
[Finished in 0.1s]
numpy.ravel

numpy.ravel ()展平的數組元素, 順序通常是"C風格", 返回數組視圖(view, 有點類似C/C++引用reference的意味), 修改會影響原始數組,

numpy.ravel(a, order = 'C')

實例:

import numpy
a = numpy.arange(8).reshape(2,4)
print('原'.center(20, '*'))
print (a)
print ('\n')
print ('調用ravel函數之後'.center(20, '*'))
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]
[Finished in 0.1s]

翻轉數組

函數 描述
transpose 對換數組的維度
ndarray.T self.transpose() 相同
rollaxis 向後滾動指定的軸
swapaxes 對換數組的兩個軸

numpy.transpose

numpy.transpose 函數用於對換數組的維度

numpy.transpose(arr, axes)

arr要操作的數組

axes整數列表, 對應維度, 通常所有維度都會對換

import numpy
a = numpy.arange(12).reshape(3,4)
print('原'.center(20, '*'))
print (a)
print ('\n')
print ('對換數組'.center(20, '*'))
print (numpy.transpose(a))
print ('\n')


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


********對換數組********
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]


[Finished in 0.2s]

numpy.ndarray.T 類似numpy.transpose:

import numpy
a = numpy.arange(12).reshape(3,4)
print('原'.center(20, '*'))
print (a)
print ('\n')
print ('轉置數組'.center(20, '*'))
print (a.T)
print ('\n')


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


********轉置數組********
[[ 0  4  8]
 [ 1  5  9]
 [ 2  6 10]
 [ 3  7 11]]


[Finished in 0.1s]
numpy.rollaxis

numpy.rollaxis函數向後滾動特定的軸到一個特定位置, 格式如下:

numpy.rollaxis(arr, axis, start)

arr數組

axis 向後滾動的軸, 其他軸的相對位置不會改變

start 默認爲0, 表示完整的滾動, 回滾到特定的位置

import numpy
a = numpy.arange(8).reshape(2,2,2)
print('原'.center(20, '*'))
print (a)
print ('\n')
# 將軸2滾動到軸0(寬度到深度)

print ('調用rollaxis函數'.center(20, '*'))
print (numpy.rollaxis(a,2))
# 將軸0 滾動到軸1位置, (寬度到高度)
print ('\n')
print ('調用rollaxis函數')
print (numpy.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]]]
[Finished in 0.1s]
numpy.swapaxes

numpy.swapaxes 函數用於交換數組的兩個軸, 格式如下:

numpy.swapaxes(arr, sxis1, axis2)

arr 數組

axis1 對應第一個軸的整數

axis2 對應第二個軸的整數

import numpy
a = numpy.arange(8).reshape(2,2,2)
print('原'.center(20, '*'))
print (a)
print ('\n')
# 現在交換軸0(深度方向)到軸2(寬度方向)

print ('調用swapaxes函數後的數組'.center(20, '*'))
print (numpy.swapaxes(a, 2, 0))

*********原**********
[[[0 1]
  [2 3]]

 [[4 5]
  [6 7]]]


**調用swapaxes函數後的數組**
[[[0 4]
  [2 6]]

 [[1 5]
  [3 7]]]
[Finished in 0.1s]

修改數組維度

維度 描述
broadcast 產生模仿廣播的對象
broadcast_to 將數組廣播到新形狀
expand_dims 擴展數組的形狀
squeeze 從數組的形狀中刪除一維條目
numpy.broadcast

numpy.broadcast 用於模仿廣播的對象, 它返回一個對象, 該對象封裝了將一個數組廣播到另一個數組的結果, 該函數使用兩個數組作爲輸入參數, 如下實例:

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 (b)
print ('對 y 廣播 x:')
r,c = b.iters
 
# Python3.x 爲 next(context) ,Python2.x 爲 context.next()
print (next(r), next(c))
print (next(r), next(c))
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)

<numpy.broadcast object at 0x55c6b266fdb0>
對 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]]
[Finished in 0.1s]
numpy.broadcast_to

numpy.broadcast_to 函數將數組廣播到新形狀, 他在原始數組上返回只讀視圖, 它通常不連續, 如果新形狀不符合numpy的廣播規則, 該函數可能會拋出ValueError

numpy.broadcast_to(array, shape, subok)
import numpy

a = numpy.arange(4).reshape(1,4)
print ('原數組:')
print (a)
print ('\n')

print ('調用broadcast_to函數之後')
print (numpy.broadcast_to(a,(2,4)))

原數組:
[[0 1 2 3]]


調用broadcast_to函數之後
[[0 1 2 3]
 [0 1 2 3]]
[Finished in 0.1s]
numpy.expand_dims

numpy.expand_dims 函數通過指定位置插入新的軸來擴展數組形狀, 函數格式:

numpy.expand_dims(arr, axis)

arr 輸入的數組

axis 新軸插入的位置, 0 表示行, 1 表示列

import numpy 

x = numpy.array(([1,2],[3,4]))
print ('數組x')
print (x)
print ('\n')
y = numpy.expand_dims(x, axis = 0)
print ('數組y')
print (y)
print ('\n')
print ('數組x和y的形狀')
print (x.shape, y.shape)
print ('\n')
# 在軸1 位置插入軸
y = numpy.expand_dims(x, axis = 1)
print ('在位置1 插入軸之後的數組')
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 插入軸之後的數組
[[[1 2]]

 [[3 4]]]


x.ndim y.ndim
2 3


x.shape, y.shape
(2, 2) (2, 1, 2)
[Finished in 0.1s]
numpy.squeeze

numpy.squeeze 從給定數組的形狀中刪除一維的條目,

numpy.squeeze(arr, axis)

arr輸入數組

axis 整數或整數元組, 用於選擇形狀中的一維條目的子集

import numpy

x = numpy.arange(9).reshape(1,3,3)
print ('數組x')
print (x)
print ('\n')
y = numpy.squeeze(x)
print ('數組y')
print (y)
print ('\n')
print ('x.shape, y.shape')
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.shape, y.shape
(1, 3, 3) (3, 3)
[Finished in 0.1s]

連接數組

函數 描述
concatenate 連接沿現有軸的數組序列
stack 沿着新的軸加入一系列數組。
hstack 水平堆疊序列中的數組(列方向)
vstack 豎直堆疊序列中的數組(行方向)
concatenate

用於沿着指定軸連接相同形狀的兩個或多個數組

numpy.concatenate((a1,a2, ...),axis)

a1,a2,a3,... 相同類型的數組

axis 沿着它連接數組的軸, 默認爲0

import numpy

a = numpy.array([[1,2],[3,4]])
print ('第一個數組')
print (a)
print ('\n')
b = numpy.array([[5,6],[7,8]])
print ('第二個數組')
print (b)
print ('\n')
# 兩個數組的維度相同

print ('沿軸0連接兩個數組:')
print (numpy.concatenate((a,b)))
print ('\n')
print ('沿着軸1連接兩個數組')
print (numpy.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]]
[Finished in 0.1s]
numpy.stack

用於沿新軸連接數組序列

numpy.stack(arrays, axis)

arrays相同形狀的數組序列

axis 返回數組中的軸, 輸入數組沿着它來堆疊

import numpy

a = numpy.array([[1,2],[3,4]])
print ('第一個數組')
print (a)
print ('\n')
b = numpy.array([[5,6],[7,8]])
print ('第二個數組')
print (b)
print ('\n')

print ('沿着0堆疊兩個數組')
print (numpy.stack((a,b),0))
print ('\n')
print ('沿着列堆疊兩個數組')
print (numpy.stack((a,b),1))


第一個數組
[[1 2]
 [3 4]]


第二個數組
[[5 6]
 [7 8]]


沿着0堆疊兩個數組
[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]


沿着列堆疊兩個數組
[[[1 2]
  [5 6]]

 [[3 4]
  [7 8]]]
[Finished in 0.1s]
numpy.hstack

是numpy.stack的變體, 通過水平堆疊來生成數組

import numpy

a = numpy.array([[1,2],[3,4]])
print ('第一個數組')
print (a)
print ('\n')
b = numpy.array([[5,6],[7,8]])
print ('第二個數組')
print (b)
print ('\n')

print ('水平堆疊')
c = numpy.hstack((a,b))
print (c)


第一個數組
[[1 2]
 [3 4]]


第二個數組
[[5 6]
 [7 8]]


水平堆疊
[[1 2 5 6]
 [3 4 7 8]]
[Finished in 0.1s]
numpy.vstack

通過垂直堆疊來生成數組

import numpy

a = numpy.array([[1,2],[3,4]])
print ('第一個數組')
print (a)
print ('\n')
b = numpy.array([[5,6],[7,8]])
print ('第二個數組')
print (b)
print ('\n')

print ('垂直堆疊')
print (numpy.vstack((a,b)))



第一個數組
[[1 2]
 [3 4]]


第二個數組
[[5 6]
 [7 8]]


垂直堆疊
[[1 2]
 [3 4]
 [5 6]
 [7 8]]
[Finished in 0.1s]

分割數組

函數 數組及操作
split 將一個數組分割爲多個子數組
hsplit 將一個數組水平分割爲多個子數組(按列)
vsplit 將一個數組垂直分割爲多個子數組(按行)
numpy.split

沿特定的軸將數組分割爲子數組

numpy.split(ary, indices_or_sections, axis)

ary 被分割的數組

indices_or_se_ctinos 如果是一個整數就用該數平均切分,如果是一個數組,爲沿軸切分的位置(左開右閉)

沿哪個維度切割 0,1

import numpy

a = numpy.arange(9)
print ('第一個數組')
print (a)
print ('\n')

print ('將數組分爲三個大小相等的子數組')
b = numpy.split(a, 3)
print (b)
print ('\n')
print ('將數組在一維數組中表明的位置分割')
b = numpy.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])]
[Finished in 0.1s]
numpy.hsplit

用於水平分割數組, 通過指定要返回的相同形狀的數組數量來拆分原數組

import numpy
harr = numpy.floor(10 * numpy.random.random((2,6)))
print ('原數組')
print (harr)

print ('拆分後')
print (numpy.hsplit(harr,3))


原數組
[[ 6.  3.  8.  0.  4.  8.]
 [ 6.  6.  7.  0.  3.  1.]]
拆分後
[array([[ 6.,  3.],
       [ 6.,  6.]]), array([[ 8.,  0.],
       [ 7.,  0.]]), array([[ 4.,  8.],
       [ 3.,  1.]])]
[Finished in 0.3s]
numpy.vsplit

沿垂直軸分割, 分割方式和hsplit相同

import numpy
a = numpy.arange(16).reshape(4,4)
print ('第一個數組:')
print (a)
print ('\n')

print ('豎直分割')
b = numpy.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]])]
[Finished in 0.1s]

數組元素的添加與刪除

函數 元素及描述
resize 返回指定形狀的新數組
append 將值添加到數組末尾
insert 沿指定軸將值插入到指定下標之前
delete 刪掉某個軸的子數組,並返回刪除後的新數組
unique 查找數組內的唯一元素
numpy.resize

返回指定大小的新數組, 如果新數組大小大於原始大小, 則包含原數組中的元素副本

numpy.resize(arr, shape)

arr 要修改大小的數組

shape 返回數組的新形狀

import numpy

a = numpy.array([[1,2,3],[4,5,6]])
print ('第一個數組')
print (a)
print ('\n')

print ('第一個數組形狀')
print (a.shape)
print ('\n')
b = numpy.resize(a,(3,2))
print ('第二個數組')
print (b)
print ('第二個數組形狀')
print (b.shape)
print ('\n')
# 注意a的第一行b中重複出現, 因爲尺寸變大了
print ('修改後的第二個數組大小')
print (numpy.resize(a,(3,3)))

第一個數組
[[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]]
[Finished in 0.1s]
numpy.append

函數在數組末尾添加值, 追加操作會分配整個數組, 並把原來的數組複製到新數組裏, 此外, 輸入數組的維度必須匹配否則將生成ValueError

append函數返回的始終是一個一維數組

numpy.append(arr, values, axis=None)
  • arr:輸入數組
  • values:要向arr添加的值,需要和arr形狀相同(除了要添加的軸)
  • axis:默認爲 None。當axis無定義時,是橫向加成,返回總是爲一維數組!當axis有定義的時候,分別爲0和1的時候。當axis有定義的時候,分別爲0和1的時候(列數要相同)。當axis爲1時,數組是加在右邊(行數要相同)。
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]]
[Finished in 0.1s]
numpy.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,22]))
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))


第一個數組
[[1 2]
 [3 4]
 [5 6]]


未傳遞axis參數, 在插入之前輸入數組會被展開
[ 1  2  3 11 22  4  5  6]


傳遞axis參數, 會廣播值數組來配輸入數組
沿軸0廣播
[[ 1  2]
 [11 11]
 [ 3  4]
 [ 5  6]]


沿軸1廣播
[[ 1 11  2]
 [ 3 11  4]
 [ 5 11  6]]

numpy.delete

返回從輸入數組中刪除指定子數組的新數組, 與insert函數一樣, 如果未提供軸參數, 輸入數組將展開

numpy.delete(arr, obj, axis)

arr 輸入數組

obj 可以被切片, 整數或者整數數組, 表明要從輸入數組刪除的子數組

axis 沿着它刪除給定子數組的軸, 如果未提供, 則輸入數組會被展開

import numpy as np

a = np.arange(12).reshape(3,4)
print (a)
print ('\n')
print ('未傳遞axis參數, 在插入之前輸入數組會被展開')
print (np.delete(a,5))
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 “bitwise_” 開頭的函數是位運算函數。

NumPy 位運算包括以下幾個函數:

函數 描述
bitwise_and 對數組元素執行位與操作
bitwise_or 對數組元素執行位或操作
invert 按位取反
left_shift 向左移動二進制表示的位
right_shift 向右移動二進制表示的位

**注:**也可以使用 “&”、 “~”、 “|” 和 “^” 等操作符進行計算。

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

以上實例可以用下表來說明:

1 1 0 1
AND
1 0 0 0 1
運算結果 0 0 0 0 1

位與操作運算規律如下:

A B AND
1 1 1
1 0 0
0 1 0
0 0 0

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

以上實例可以用下表來說明:

1 1 0 1
OR
1 0 0 0 1
運算結果 1 1 1 0 1

位或操作運算規律如下:

A B OR
1 1 1
1 0 1
0 1 1
0 0 0

invert

函數對數組中整數進行取反運算, 0變爲1, 1變爲0

對於有符號的整數, 取該二進制的補碼然後+1 二進制數, 最高位爲0表示整數, 最高位爲1 表示負數

看看 ~1 的計算步驟:

  • 1(這裏叫:原碼)轉二進制 = 00000001

  • 按位取反 = 11111110

  • 發現符號位(即最高位)爲1(表示負數),將除符號位之外的其他數字取反 = 10000001

  • 末位加1取其補碼 = 10000010

  • 轉換回十進制 = -2

  • 表達式 二進制值(2 的補數) 十進制值
    5 00000000 00000000 00000000 0000010 5
    ~5 11111111 11111111 11111111 11111010 -6
import numpy as np

print ('13的位反轉,其中ndarra的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的位反轉,其中ndarra的dtype是uint8
[242]


13的二進制表示:
00001101


242的二進制表示
11110010

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 ('40的二進制表示')
print (np.binary_repr(40, width = 8))
# '00001010'中的兩位移動到左邊, 並在右邊添加了兩個0



將10向左移動兩位
40


10的二進制表示
00001010
40的二進制表示
00101000

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 內置庫中的標準字符串函數。

這些函數在字符數組類(numpy.char)中定義。

函數 描述
add() 對兩個數組的逐個字符串元素進行連接
multiply() 返回按元素多重連接後的字符串
center() 居中字符串
capitalize() 將字符串第一個字母轉換爲大寫
title() 將字符串的每個單詞的第一個字母轉換爲大寫
lower() 數組元素轉換爲小寫
upper() 數組元素轉換爲大寫
split() 指定分隔符對字符串進行分割,並返回數組列表
splitlines() 返回元素中的行列表,以換行符分割
strip() 移除元素開頭或者結尾處的特定字符
join() 通過指定分隔符來連接數組中的元素
replace() 使用新字符串替換字符串中的所有子字符串
decode() 數組元素依次調用str.decode
encode() 數組元素依次調用str.encode

numpy.char.add()

依次對兩個數組的元素進行字符串連接

import numpy as np

print ('連接兩個字符串')
print (np.char.add(['hello'],['word']))
print ('連接示列')
print (np.char.add(['hello', 'hi'],['word','world']))

連接兩個字符串
['helloword']
連接示列
['helloword' 'hiworld']

numpy.char.multiply()

執行多重連接

import numpy as np

print (np.char.multiply('python', 5))

pythonpythonpythonpythonpython

numpy.char.center()

函數用於將字符串居中, 並使用指定字符在左側和右側進行填充

np.char.center(str, width, fillchar)
str: 字符串, width:長度, fillchar: 填充字符
import numpy as np

print (np.char.center('python', 20, fillchar = '*'))


*******python*******

numpy.char.capitalize()

將字符串的第一個字母裝換爲大寫

>>> import numpy as np
>>> print (np.char.capitalize('python')
... )
Python

numpy.char.title()

字符串的每個單詞的第一個字母轉換爲大寫

>>> import numpy as np
>>> print (np.char.title('i love python'))
I Love Python

numpy.char.lower()

對數組的每個元素轉換爲小寫, 對每個元素調用str.lower

>>> print (np.char.lower(['HELLO','PYTHON'])) # 操作數組
['hello' 'python']
>>> print (np.char.lower('PYTHON')) # 操作字符串
python

numpy.char.upper()

將數組每個元素轉換成大寫, 同char.lower()

numpy.char.split()

通過指定分隔符對字符串進行分割,並返回數組。默認情況下,分隔符爲空格。

>>> print (np.char.split('i love python')) # 默認分割符爲空格
['i', 'love', 'python']
>>> print (np.char.split('pigdaqiang.top', sep = '.')) # 指定分隔符爲 .
['pigdaqiang', 'top']

numpy.char.splitlines()

以換行符作爲分隔符, 並返回數組

>>> print (np.char.splitlines('i\r\nlove python'))
['i', 'love python']
>>> print (np.char.splitlines('i\rlove python'))
['i', 'love python']

注意區別linux下和win下換行符的區別 \r \n \r\n

numpy.char.strip()

用於移除開頭或結尾處的特定字符

>>> print (np.char.strip('hhello', 'h')) # 移除字符串頭尾的h字符
ello
>>> 
>>> print (np.char.strip(['hello','hi','high'],'h')) # 移除數組元素頭尾的a字符
['ello' 'i' 'ig']
>>> 

numpy.char.join()

通過指定分割符來連接數組中的元素或字符串

>>> print (np.char.join(':','hello'))
h:e:l:l:o
>>> print (np.char.join([':','*'],['hello','python']))
['h:e:l:l:o' 'p*y*t*h*o*n']
>>> 

numpy.char.replace()

使用新字符串代替字符串中的所有子字符串

>>> print (np.char.replace('i love python',' ','*'))
i*love*python
>>> 

numpy.char.encode()

函數對數組中的每個元素調用str.encode函數, 默認編碼是utf-8, 可以使用標準python庫中的編解碼器

>>> print (np.char.encode('hello','cp500'))
b'\x88\x85\x93\x93\x96'
>>> 

numpy.char.decode()

函數對編碼的元素進行str.encode()解碼

>>> a = np.char.encode('hello', 'cp500')
>>> print (a, np.char.decode(a, 'cp500'))
b'\x88\x85\x93\x93\x96' hello
>>> 

numpy數學函數

NumPy 包含大量的各種數學運算的函數,包括三角函數,算術運算的函數,複數處理函數等。

三角函數

NumPy 提供了標準的三角函數:sin()、cos()、tan()。

import numpy as np

a = np.array([0,20,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.34202014  0.70710678  0.8660254   1.        ]


數組中角度的餘玄值
[  1.00000000e+00   9.39692621e-01   7.07106781e-01   5.00000000e-01
   6.12323400e-17]


數組中角度的正切值
[  0.00000000e+00   3.63970234e-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(a, decimals)

a 數組

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()

返回小於或者等於指定表達式的最大整數, 向下取整

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()

返回大於或者等於指定表達式的最小整數, 即向上取整. 用法同floor

numpy算術函數

算術函數包含簡單的加減乘除:add(), substract(), 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.reciprocal()

返回參數逐元素的倒數, 1/4倒數4/1

import numpy as np

a = np.array([0.25, 1.33, 1, 100])
print (a)
print ('倒數')
print (np.reciprocal(a))


[   0.25    1.33    1.    100.  ]
倒數
[ 4.         0.7518797  1.         0.01     ]

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 ('再次調用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 ('調用mod')
print (np.mod(a,b))
print ('調用remainder')
print (np.remainder(a,b))


調用mod
[1 0 2]
調用remainder
[1 0 2]

numpy 統計函數

從數組中查找最小元素, 最大元素, 百分位標準差, 和方差燈

numpy.amin()和numpy.amax()

numpy.amin() 用於計算數組中的元素沿指定軸的最小值。

numpy.amax() 用於計算數組中的元素沿指定軸的最大值。

import numpy as np

a = np.array([[3,5,7],[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 ('調用amax')
print (np.amax(a))
print ('\n')
print ('再次調用amax')
print (np.amax(a, axis = 0))


原數組
[[3 5 7]
 [8 4 3]
 [2 4 9]]


調用amin()函數
[3 3 2]


再次調用amin
[2 4 3]
調用amax
9


再次調用amax
[8 5 9]

numpy.ptp()

計算元素最大值與最小值的差(最大值-最小值)

import numpy as np

a = np.array([[3,5,7],[8,4,3],[2,4,9]])
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 5 7]
 [8 4 3]
 [2 4 9]]


調用ptp函數
7


沿軸1調用ptp函數
[4 5 7]


沿軸0調用ptp函數
[6 1 6]

numpy.percentile()

百分數是統計中使用的度量, 表示小於這個值的觀察值的百分比.

numpy.percentile(a, q, axis)

a 輸入數組

q 要計算的百分位數, 在0-100之間

axis 沿着它計算百分位數的軸

首先明確百分位數:

第 p 個百分位數是這樣一個值,它使得至少有 p% 的數據項小於或等於這個值,且至少有 (100-p)% 的數據項大於或等於這個值。

舉個例子:高等院校的入學考試成績經常以百分位數的形式報告。比如,假設某個考生在入學考試中的語文部分的原始分數爲 54 分。相對於參加同一考試的其他學生來說,他的成績如何並不容易知道。但是如果原始分數54分恰好對應的是第70百分位數,我們就能知道大約70%的學生的考分比他低,而約30%的學生考分比他高。

這裏的 p = 70。

import numpy as np

a = np.array([[10,7,4], [3,2,1]])
print (a)
print ('調用percentile函數')
# 50%的分位數就是a裏排序之後的中位數
print (np.percentile(a, 50))
# axis爲0 , 在縱列上求
print (np.percentile(a,50, axis = 0))
# 橫行上求
print (np.percentile(a, 50, axis = 1))
# 維度不變
print (np.percentile(a, 50, axis = 1, keepdims = True))


[[10  7  4]
 [ 3  2  1]]
調用percentile函數
3.5
[ 6.5  4.5  2.5]
[ 7.  2.]
[[ 7.]
 [ 2.]]

numpy.median()

函數用於計算數組a中元素的中位數(中值)

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()

函數返回數組中元素的算術平均值, 如果提供了軸, 則沿其計算, 算術平均值是沿軸的元素總和除以元素的數量

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()

函數根據在另一個數組中給出的各自的權重計算數組中元素的加權平均值。

該函數可以接受一個軸參數。 如果沒有指定軸,則數組會被展開。

加權平均值即將各數值乘以相應的權數,然後加總求和得到總體值,再除以總的單位數。

考慮數組[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()

標準差是一組數據平均值分散程度的一種度量。

標準差是方差的算術平方根。

標準差公式如下:

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.11803398875

方差var()

統計中的方差(樣本方差)是每個樣本值與全體樣本值的平均數之差的平方值的平均數,即 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()

返回輸入數組的排序副本

numpy.sort(a, axis, kind, order)

a 要排序的數組

axis 沿着它排序數組的軸, 如果沒有數組會被展開, 沿着最後的軸排序, axis = 0 按列排序, axis=1 按行

kind 默認爲quicksort (快速排序)

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 ('按列排序')
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 = d
t)
print ('原數組')
print (a)
print ('\n')
print ('按name排序')
print (np.sort(a,order = 'name'))


原數組
[[3 7]
 [9 1]]


調用sort函數
[[3 7]
 [1 9]]


按列排序
[[3 1]
 [9 7]]


原數組
[(b'raju', 21) (b'anil', 25) (b'ravi', 17) (b'amar', 27)]


按name排序
[(b'amar', 27) (b'anil', 25) (b'raju', 21) (b'ravi', 17)]

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], end = ' ')


原數組
[3 1 2]


對x調用argsort函數
[1 2 0]


以排序後的順序重構原數組
[1 2 3]


使用循環重構原數組
1 2 3 

numpy.lexsort()

用於對多個序列進行排序。把它想象成對電子表格進行排序,每一列代表一個序列,排序時優先照顧靠後的列。

這裏舉一個應用場景:小升初考試,重點班錄取學生按照總成績錄取。在總成績相同時,數學成績高的優先錄取,在總成績和數學成績都相同時,按照英語成績錄取…… 這裏,總成績排在電子表格的最後一列,數學成績在倒數第二列,英語成績在倒數第三列。

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.']

上面傳入一個np.lexsort的是一個ruple, 排序是首先排nm, 順序爲amar, anil, raju, ravi 綜上排序結果爲[3 1 0 2]

msort sort_complex partition argpartition

函數 描述
msort(a) 數組按第一個軸排序,返回排序後的數組副本。np.msort(a) 相等於 np.sort(a, axis=0)。
sort_complex(a) 對複數按照先實部後虛部的順序進行排序。
partition(a, kth[, axis, kind, order]) 指定一個數,對數組進行分區
argpartition(a, kth[, axis, kind, order]) 可以通過關鍵字 kind 指定算法沿着指定軸對數組進行分區
>>> import numpy as np
>>> np.sort_complex([5,3,6,2,1])
array([ 1.+0.j,  2.+0.j,  3.+0.j,  5.+0.j,  6.+0.j])
>>> np.sort_complex([1+2j, 2-1j, 3-2j, 3-3j, 3+5j])
array([ 1.+2.j,  2.-1.j,  3.-3.j,  3.-2.j,  3.+5.j])
>>> 

import numpy as np

a = np.array([3,4,2,1])
print (np.partition(a,3)) # 將數組a中的所有元素(包括重複元素) 從小到大排列, 3 
表示的是排序數組索引爲3的數字, 比該數字小的排在該數字前面, 比該數字大的排在該數
字的後面
print (np.partition(a, (1,3))) # 小於1的在前面, 大於3的在後面, 1和3之間的在中間
'''
找到數組的第三小(index=2)的值和第二大index=-2的值
'''
arr = np.array([46,57,23,39,1,10,0,120])
print (arr[np.argpartition(arr, 2)[2]])
print (arr[np.argpartition(arr, -2)[-2]])
'''
同時找到第三和第四小的值, 注意這裏用[2,3]同時將第3和第四小的排序, 然後可以分別
通過下標[2]和[3]取得
'''
print (arr[np.argpartition(arr, [2,3])[2]])
print (arr[np.argpartition(arr, [2,3])[3]])


[2 1 3 4]
[1 2 3 4]
10
57
10
23

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()

函數返回輸入數組中非0元素的索引

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()

返回輸入數組中滿足給定條件的元素的索引

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()

根據某個條件從數組中抽取元素, 返回滿條件的元素

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字節交換

在幾乎所有的機器上,多字節對象都被存儲爲連續的字節序列。字節順序,是跨越多字節的程序對象的存儲規則。

  • **大端模式:**指數據的高字節保存在內存的低地址中,而數據的低字節保存在內存的高地址中,這樣的存儲模式有點兒類似於把數據當作字符串順序處理:地址由小向大增加,而數據從高位往低位放;這和我們的閱讀習慣一致。
  • **小端模式:**指數據的高字節保存在內存的高地址中,而數據的低字節保存在內存的低地址中,這種存儲模式將地址的高低和數據位權有效地結合起來,高地址部分權值高,低地址部分權值低。

例如在 C 語言中,一個類型爲 int 的變量 x 地址爲 0x100,那麼其對應地址表達式&x的值爲 0x100。且x的四個字節將被存儲在存儲器的 0x100, 0x101, 0x102, 0x103位置。

字節交換

numpy.ndarray.byteswap()

將ndarray中每個元素中的字節進行大小端轉換

import numpy as np

a = np.array([1, 256, 8755], dtype = np.int16)
print ('原數組')
print (a)
print ('以16進製表示內存中的數據')
print (map(hex, a))
# btypeswap()函數通過傳入true來原地交換
print ('調用byteswap函數')
print (a.byteswap(True))
print ('16進制')
print (map(hex, a))
# 字節交換


原數組
[   1  256 8755]
以16進製表示內存中的數據
<map object at 0x7fc8ff886898>
調用byteswap函數
[  256     1 13090]
16進制
<map object at 0x7fc8fa7d2ef0>

副本和視圖(深拷貝和淺拷貝)

副本是一個數據的完整的拷貝,如果我們對副本進行修改,它不會影響到原始數據,物理內存不在同一位置。

視圖是數據的一個別稱或引用,通過該別稱或引用亦便可訪問、操作原有數據,但原有數據不會產生拷貝。如果我們對視圖進行修改,它會影響到原始數據,物理內存在同一位置。

視圖一般發生在:

  • 1、numpy 的切片操作返回原數據的視圖。
  • 2、調用 ndarray 的 view() 函數產生一個視圖。

副本一般發生在:

  • Python 序列的切片操作,調用deepCopy()函數。
  • 調用 ndarray 的 copy() 函數產生一個副本。

無複製

簡單的賦值不會創建數組對象的副本。 相反,它使用原始數組的相同id()來訪問它。 id()返回 Python 對象的通用標識符,類似於 C 中的指針。

此外,一個數組的任何變化都反映在另一個數組上。 例如,一個數組的形狀改變也會改變另一個數組的形狀。

矩陣(Matrix)

NumPy 中包含了一個矩陣庫 numpy.matlib,該模塊中的函數返回的是一個矩陣,而不是 ndarray 對象。

一個 img的矩陣是一個由img行(row)img列(column)元素排列成的矩形陣列。

矩陣裏的元素可以是數字、符號或數學式。以下是一個由 6 個數字元素構成的 2 行 3 列的矩陣:

img

matlib.empty()

返回一個新矩陣

numpy.matlib.empty(shape, dtype, order)

shape 定義新矩陣的整數或 整數元組

dtype可選, 數據類型

order c或者f

import numpy.matlib
import numpy as np

print (np.matlib.empty((2,2)))
# 填充爲隨機數

[[  6.91000091e-310   4.68077452e-310]
 [  6.90999951e-310   0.00000000e+000]]

numpy.matlib.zeros()

創建一個以0填充的矩陣

import numpy.matlib
import numpy as np

print (np.matlib.zeros((2,2)))

[[ 0.  0.]
 [ 0.  0.]]

numpy.matlib.ones()

創建一個以1填充的矩陣

numpy.matlib.ones((2,2))

numpy.matlib.eye()

返回一個矩陣, 對角元素爲1, 其他位置爲0

numpy.matlib.eye(n, M, k, dtype)

n 返回矩陣的行數

M 返回矩陣的列數, 默認爲n

k 對角線的索引

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()

返回給定大小的單位矩陣

單位矩陣是個方陣, 從左上角到右下角的對角線(稱爲主對角線)上的元素均爲1, 除此以外全都爲0

import numpy.matlib
import numpy as np

print (np.matlib.identity(5, dtype = float))
# 大小爲5, 類型爲浮點數

[[ 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(3,3)

矩陣是二維的, ndarray是一個n維數組, 兩個對象是可互換的

import numpy.matlib
import numpy as np

i = np.matrix('1,2;3,4')
print (i)
[[1 2]
 [3 4]]

j = np.asarray(i)
print (j)

[[1 2]
 [3 4]]
k = np.asmatrix(j)
print (k)

[[1 2]
 [3 4]]

線性代數

NumPy 提供了線性代數函數庫 linalg,該庫包含了線性代數所需的所有功能,可以看看下面的說明:

函數 描述
dot 兩個數組的點積,即元素對應相乘。
vdot 兩個向量的點積
inner 兩個數組的內積
matmul 兩個數組的矩陣積
determinant 數組的行列式
solve 求解線性矩陣方程
inv 計算矩陣的乘法逆矩陣

numpy.dot()

numpy.dot() 對於兩個一維的數組,計算的是這兩個數組對應下標元素的乘積和(數學上稱之爲內積);對於二維數組,計算的是兩個數組的矩陣乘積;對於多維數組,它的通用計算公式如下,即結果數組中的每個元素都是:數組a的最後一維上的所有元素與數組b的倒數第二位上的所有元素的乘積和: dot(a, b)[i,j,k,m] = sum(a[i,j,:] * b[k,:,m])。

numpy.dot(a, b, out=None)

a ndarray數組

bndarray 數組

out ndarray 可選用來保存dot()的計算結果

import numpy.matlib
import numpy as np

a = np.array([[1,2],[3,4]])
b = np.array([[11,12],[13,14]])
print (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()

兩個向量的點積, 如果第一個參數是複數, 那麼它的共軛複數用於計算, 如果參數是多維數組, 他會被展開

import numpy as np

a = np.array([[1,2], [3, 4]])
b = np.array([[11, 12], [13, 14]])
# vdot 將數組展開計算內積
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, 22], [13, 14]])
print ('數組b')
print (b)
print ('內積')
print (np.inner(a, b))


數組a
[[1 2]
 [3 4]]
數組b
[[11 22]
 [13 14]]
內積
[[ 55  41]
 [121  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()

numpy.linalg.det() 函數計算輸入矩陣的行列式。

行列式在線性代數中是非常有用的值。 它從方陣的對角元素計算。 對於 2×2 矩陣,它是左上和右下元素的乘積與其他兩個的乘積的差。

換句話說,對於矩陣[[a,b],[c,d]],行列式計算爲 ad-bc。 較大的方陣被認爲是 2×2 矩陣的組合。


import numpy as np

a = np.array([[1, 2], [3, 4]])
print (np.linalg.det(a))


-2.0
import numpy as np

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()

給出了矩陣形式的線性方程的解

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() 函數計算矩陣的乘法逆矩陣。

逆矩陣(inverse matrix):設A是數域上的一個n階矩陣,若在相同數域上存在另一個n階矩陣B,使得: AB=BA=E ,則我們稱B是A的逆矩陣,而A則被稱爲可逆矩陣。注:E爲單位矩陣。

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]]

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 IO

可以讀寫磁盤上的文本數據或者二進制數據. 爲ndarray對象引入了一個簡單的文本格式, npy

npy文件用於存儲重建ndarray所需的數據, 圖形, dtype和其他信息.

常用IO函數有:

  • load() 和 save() 函數是讀寫文件數組數據的兩個主要函數,默認情況下,數組是以未壓縮的原始二進制格式保存在擴展名爲 .npy 的文件中。
  • savze() 函數用於將多個數組寫入文件,默認情況下,數組是以未壓縮的原始二進制格式保存在擴展名爲 .npz 的文件中。
  • loadtxt() 和 savetxt() 函數處理正常的文本文件(.txt 等)

numpy.save()

將數組保存到以.npy爲擴展名的文件中

numpy.save(file, arr, allow_pickle=True, fix_imports=True)
  • file:要保存的文件,擴展名爲 .npy,如果文件路徑末尾沒有擴展名 .npy,該擴展名會被自動加上。
  • arr: 要保存的數組
  • allow_pickle: 可選,布爾值,允許使用 Python pickles 保存對象數組,Python 中的 pickle 用於在保存到磁盤文件或從磁盤文件讀取之前,對對象進行序列化和反序列化。
  • fix_imports: 可選,爲了方便 Pyhton2 中讀取 Python3 保存的數據。
import numpy as np

a = np.array([1,2,3,4,5])
# 保存到outfile.npy文件上
np.save('outfile.npy', a)
# 保存到outfile2.npy文件上, 如果文件 路徑末尾沒有.npy, 則會自動加上
np.save('outfile2', a)


pig@deep:~/Desktop/note/python/numpy$ cat outfile.npy
�NUMPYF{'descr': '<i8', 'fortran_order': False, 'shape': (5,), }            
pig@deep:~/Desktop/note/python/numpy$ cat outfile2.npy 
�NUMPYF{'descr': '<i8', 'fortran_order': False, 'shape': (5,), }            
p

可以看出文件是亂碼的,因爲它們是 Numpy 專用的二進制格式後的數據。

我們可以使用 load() 函數來讀取數據就可以正常顯示了:

import numpy as np
b = np.load('outfile.npy')
print (b)


[1 2 3 4 5]

numpy.savez

將多個數組保存到以npz爲拓展名的文件中

numpy.savez(file, *arg, **kwds)
  • file:要保存的文件,擴展名爲 .npz,如果文件路徑末尾沒有擴展名 .npz,該擴展名會被自動加上。
  • args: 要保存的數組,可以使用關鍵字參數爲數組起一個名字,非關鍵字參數傳遞的數組會自動起名爲 arr_0, arr_1, … 。
  • kwds: 要保存的數組使用關鍵字名稱。
import numpy as np

a = np.array([[1,2,3], [4,5,6]])
b = np.arange(0,1.0,0.1)
c = np.sin(b)
# c使用了關鍵字參數sin_array
np.savez('savez.npz', a, b, sin_array = c)
r = np.load('savez.npz')
print (r.files) # 查看個數組名稱
print (r['arr_0']) # 數組a
print (r['arr_1'])
print (r['sin_array']) # 數組c


['arr_1', 'sin_array', 'arr_0']
[[1 2 3]
 [4 5 6]]
[ 0.   0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9]
[ 0.          0.09983342  0.19866933  0.29552021  0.38941834  0.47942554
  0.56464247  0.64421769  0.71735609  0.78332691]

savetxt()

是以簡單的文本格式存儲數據 , 對應的使用loadtxt函數來獲取數據

np.loadtxt(FILENAME, dtype=int, delimiter='')
np.savetxt(FILENAME, a, fmt='%d', delimiter=",")

delimiter可以指定各種分隔符, 針對特定列的轉換器函數, 需要跳過的行數等.

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.]

使用delimiter參數:

import numpy as np

a = np.arange(0, 10, 0.5).reshape(4,-1)
np.savetxt('out2.txt', a, fmt="%d", delimiter="*") # 改爲保存整數, 以逗號分隔
b = np.loadtxt("out2.txt", delimiter="*") # load時也要指定爲相同符號分隔
print (b)


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

matplotlib

Matplotlib 是 Python 的繪圖庫。 它可與 NumPy 一起使用,提供了一種有效的 MatLab 開源替代方案。 它也可以和圖形工具包一起使用,如 PyQt 和 wxPython。

wim下安裝matplotlib:

python -m pip install -U pip setuptools
python -m pip install matplotlib

linux下:

sudo apt-get install python-matplotlib

mac:

sudo python -mpip install matplotlib

查看是否安裝完成:

python -m pip list | grep matplotlib
matplotlib                    2.2.4  

實例

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(1,11)
y = 2 * x + 5
plt.title("test demo")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x, y)
plt.show()

plt1

以上實例中, np.arange()函數創建x軸上的值, y軸上對應值存儲在另一個數組對象y中, 這些值使用matplotlib軟件包的pyplot子模塊plot()函數來繪製, 由show()函數來顯示

圖形中文顯示

默認情況下不支持中文, 可以使用以下方法(下載字體)https://www.fontpalace.com/font-details/SimHei/

SimHei.ttf文件放在當前執行的代碼文件中.

import numpy as np 
from matplotlib import pyplot as plt 
import matplotlib
 
# fname 爲 你下載的字體庫路徑,注意 SimHei.ttf 字體的路徑
zhfont1 = matplotlib.font_manager.FontProperties(fname="SimHei.ttf") 
 
x = np.arange(1,11) 
y =  2  * x +  5 
plt.title("測試", fontproperties=zhfont1) 
 
# fontproperties 設置中文顯示,fontsize 設置字體大小
plt.xlabel("x 軸", fontproperties=zhfont1)
plt.ylabel("y 軸", fontproperties=zhfont1)
plt.plot(x,y) 
plt.show()

此外還可以使用系統字體:

from matplotlib import pyplot as plt
import matplotlib
a = sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist])
for i in a:
	print (i)
	
打印出你的font_manage的ttflist中所有註冊的名字, 找一個看中文字體例如:STFangsong(仿宋)然後添加以下代碼即可:
plt.rcParams['font.family']=['STFangsong']

實例:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib

# 導入系統字體庫
plt.rcParams['font.family']=['CESI_HT_GB18030']
x = np.arange(0, 2 * np.pi, 0.001)
y = np.sin(x)
plt.title("測試")
plt.xlabel("x軸")
plt.ylabel("y軸")
plt.plot(x, y)
plt.show()

plt2

作爲線性圖的替代,可以通過向 plot() 函數添加格式字符串來顯示離散值。 可以使用以下格式化字符。

字符 描述
'-' 實線樣式
'--' 短橫線樣式
'-.' 點劃線樣式
':' 虛線樣式
'.' 點標記
',' 像素標記
'o' 圓標記
'v' 倒三角標記
'^' 正三角標記
'&lt;' 左三角標記
'&gt;' 右三角標記
'1' 下箭頭標記
'2' 上箭頭標記
'3' 左箭頭標記
'4' 右箭頭標記
's' 正方形標記
'p' 五邊形標記
'*' 星形標記
'h' 六邊形標記 1
'H' 六邊形標記 2
'+' 加號標記
'x' X 標記
'D' 菱形標記
'd' 窄菱形標記
'&#124;' 豎直線標記
'_' 水平線標記

以下是顏色的縮寫:

字符 顏色
'b' 藍色
'g' 綠色
'r' 紅色
'c' 青色
'm' 品紅色
'y' 黃色
'k' 黑色
'w' 白色

要顯示圓來代表點,而不是上面示例中的線,請使用 ob 作爲 plot() 函數中的格式字符串。

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(0, 2 * np.pi, 0.1)
y = np.cos(x)
plt.title("sin")
plt.xlabel("x axis caption")
plt.ylabel("y axis caption")
plt.plot(x, y, ".b")
plt.show()

plt3.png

繪製正弦波

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 3 * np.pi, 0.1)
y = np.sin(x)
plt.title("sine")
plt.plot(x, y, '.b')
plt.show()

subplot()

允許在同一圖中繪製不同的東西

正弦餘弦

import numpy as np
import matplotlib.pyplot as plt

# 計算正弦和餘弦曲線上的點x和y座標
x = np.arange(0, 2 * np.pi, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# 建立subplot網格 高爲1, 寬爲2
# 激活第一個subplot
plt.subplot(1, 2, 1)
# 繪製第一個圖像
plt.plot(x, y_sin)
plt.title("sine")

# 激活第二個subplot並繪製第二個圖像
plt.subplot(1, 2, 2)
plt.plot(x, y_cos)
plt.title("cosine")

# 展示圖像
plt.show()

plt.subplot(1,2,1) 不同參數的區別

plt4

bar()

pyplot 子模塊提bar()函數來生成條形圖

實現兩組x 和y數組的條形圖

import matplotlib.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()

bar

numpy.histogram()

是數據頻率分佈的圖形表示, 水平尺寸相等的矩形對應於類間隔, 稱爲bin, 變量height對應與頻率

將輸入數組和bin作爲兩個參數, bin數組中連續元素用作每個bin的邊界

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()

p

參考教程:菜鳥教程
個人博客
簡書numpy學習(一)
簡書numpy學習(二)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章