回顧:
為什么用 NumPy?
NumPy 是一個用于科學計算的基礎 Python 庫(安裝說明)募强。它可以讓你在 Python 中使用向量和數(shù)學矩陣,以及許多用 C 語言實現(xiàn)的底層函數(shù)祭椰。
-
簡潔優(yōu)雅
當下大部分數(shù)據(jù)的組織結構是向量、矩陣或多維數(shù)組,NumPy 最重要的一個特點是 N 維數(shù)組對象(ndarray)。
-
效率高
方便地計算一組數(shù)值府蛇,而不用寫復雜的循環(huán)。
-
靈活兼容
除了擅長科學計算屿愚,NumPy 還可以用作通用數(shù)據(jù)多維容器,可無縫對接各種各樣的數(shù)據(jù)庫务荆。
-
敲門磚
在數(shù)據(jù)科學中妆距,有效的存儲和操作數(shù)據(jù)是基礎能力。如果想通過 Python 學習數(shù)據(jù)科學或者機器學習函匕,就必須學習 NumPy娱据。
在 Notebook 中導入 NumPy:
import numpy as np
什么是數(shù)組
數(shù)組是將數(shù)據(jù)組織成若干個維度的數(shù)據(jù)塊。
Array : data about relationships
- 一維數(shù)組是向量(Vectors)盅惜,由一個整數(shù)索引有序元素序列中剩。
- 二維數(shù)組是矩陣(Matrics),用一對整數(shù)(行索引和列索引)索引元素抒寂。
- N 維數(shù)組(Arrays)是一組由 n 個整數(shù)的元組進行索引的结啼、具有相同數(shù)據(jù)類型的元素集合。
創(chuàng)建數(shù)組
NumPy 的核心是數(shù)組(arrays)屈芜。
用 array
創(chuàng)建數(shù)組
In[]: np.array([1, 4, 2, 5, 3])
Out[]: array([1, 4, 2, 5, 3])
在 NumPy 數(shù)組中郊愧,數(shù)據(jù)類型需要一致朴译,否則,會嘗試「向上兼容」属铁,比如生成一個包含浮點數(shù)的數(shù)組眠寿,輸出時每個元素都變成了浮點型:
In[]: np.array([3.14, 4, 2, 3])
Out[]: array([ 3.14, 4. , 2. , 3. ])
NumPy 還可以用循環(huán)生成數(shù)組:
In[]: np.array([range(i, i + 3) for i in [2, 4, 6]])
Out[]: array([[2, 3, 4],
[4, 5, 6],
[6, 7, 8]])
用 full
生成一個 3 行 5 列的數(shù)組:
In[]: np.full((3, 5), 3.14)
Out[]: array([[ 3.14, 3.14, 3.14, 3.14, 3.14],
[ 3.14, 3.14, 3.14, 3.14, 3.14],
[ 3.14, 3.14, 3.14, 3.14, 3.14]])
用 arange
等距填充數(shù)組:
(arange 是 Python 內置函數(shù) range 的數(shù)組版,返回的是一個 ndarray 而不是 list)
# Starting at 0, ending at 20, stepping by 2
In[]: np.arange(0, 20, 2)
Out[]: array([ 0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
用 linspace
線性填充數(shù)組:
# Create an array of five values evenly spaced between 0 and 1
In[]: np.linspace(0, 1, 5)
Out[]: array([ 0. , 0.25, 0.5 , 0.75, 1. ])
用 random
生成隨機數(shù)組:
# Create a 3x3 array of random integers in the interval [0, 10)
In[]: np.random.randint(0, 10, (3, 3))
Out[]: array([[2, 3, 4],
[5, 7, 8],
[0, 5, 0]])
btw 數(shù)組索引從 0 開始
數(shù)組切片
NumPy 中的切片語法:x[start:stop:step]
焦蘑,如果沒有賦值盯拱,默認值 start=0, stop=size of dimension, step=1。
(上圖最后一個圖形例嘱,arr[1, :2] 應該是 (1,2) 一行二列矩陣狡逢??)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In[]: x[::2] # every other element
Out[]:array([0, 2, 4, 6, 8])
array([[12, 5, 2, 4],
[ 7, 6, 8, 8],
[ 1, 6, 7, 7]])
In[]: x2[:3, ::2] # all rows, every other column
Out[]:array([[12, 2],
[ 7, 8],
[ 1, 7]])
復制數(shù)組切片
x2 = array([[99 5 2 4]
[ 7 6 8 8]
[ 1 6 7 7])
In[]: x2_sub_copy = x2[:2, :2].copy()
print(x2_sub_copy)
Out[]:[[99 5]
[ 7 6]]
數(shù)組轉置和軸對換
reshape:
In[]: arr = np.arange(15).reshape((3,5))
arr
Out[]: array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
轉置(transpose)是重塑(reshape)的一種特殊形式蝶防,返回源數(shù)據(jù)的視圖而不進行復制甚侣。
In[]: arr.T
Out[]: array([[ 0, 5, 10],
[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14]])
連接和拆分數(shù)組
用concatenate
連接數(shù)組:
In[]: grid = np.array([[1, 2, 3],
[4, 5, 6]])
np.concatenate([grid, grid])
Out[]: array([[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6]])
# concatenate along the second axis (zero-indexed)
In[]: np.concatenate([grid, grid], axis=1)
Out[]: array([[1, 2, 3, 1, 2, 3],
[4, 5, 6, 4, 5, 6]])
用 vstack
合并到數(shù)據(jù)行, hstack
合并到數(shù)據(jù)列
In[]: x = np.array([1, 2, 3])
grid = np.array([[9, 8, 7],
[6, 5, 4]])
# vertically stack the arrays
np.vstack([x, grid])
Out[]:array([[1, 2, 3],
[9, 8, 7],
[6, 5, 4]])
拆分數(shù)組的函數(shù)包括: np.split, np.hsplit, np.vsplit
In[]: x = np.arange(8.0)
np.split(x, [3, 5, 6, 10])
Out[]: [array([ 0., 1., 2.]),
array([ 3., 4.]),
array([ 5.]),
array([ 6., 7.]),
array([], dtype=float64)]
使用 mask
快速截取數(shù)據(jù)
傳遞給數(shù)組一個與它有關的條件式间学,然后它就會返回給定條件下為真的值殷费。
In[]: norm10 = np.random.normal(10,3,5)
mask = norm10 > 9
mask
Out[]:array([False, True, False, True, False], dtype=bool)
In[]: print('Values above 9:', norm10[mask])
Out[]: ('Values above 9:', array([ 13.69383139, 13.49584954]))
在生成圖形時也非常好用:
import matplotlib.pyplot as plt
a = np.linspace(0, 2 * np.pi, 50)
b = np.sin(a)
plt.plot(a,b)
mask = b >= 0
plt.plot(a[mask], b[mask], 'bo')
mask = (b >= 0) & (a <= np.pi / 2)
plt.plot(a[mask], b[mask], 'go')
plt.show()
在程序中用條件式選擇了圖中不同的點。藍色的點(也包含圖中的綠點低葫,只是綠點覆蓋了藍點)详羡,顯示的是值大于零的點。綠點顯示的是值大于 0 小于 Pi / 2 的點嘿悬。
廣播 Broadcasting
當不同 shape 的數(shù)組進行運算(按位加/按位減的運算实柠,而不是矩陣乘法的運算)時,(某個維度上)小的數(shù)組就會沿著(同一維度上)大的數(shù)組自動填充善涨。廣播雖然是一個不錯的偷懶辦法窒盐,但是效率不高、降低運算速度通常也為人詬病钢拧。
The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes.
via Broadcasting — NumPy v1.13 Manual
廣播的原理(via Broadcast Visualization):
參考資料
- NumPy.org
- Python Data Science Handbook
- 利用Python進行數(shù)據(jù)分析
- Scipy lecture notes
- Enter The Matrix
- 使用 Python 進行科學計算:NumPy入門
- Broadcasting — NumPy v1.13 Manual
- EricsBroadcastingDoc - SciPy wiki dump
- Broadcast Visualization — astroML 0.2 documentation