相关文章推荐
耍酷的书签  ·  Avoiding Type 3 fonts ...·  2 月前    · 
耍酷的书签  ·  Examples — Matplotlib ...·  2 月前    · 
耍酷的书签  ·  Matplotlib ...·  2 月前    · 
耍酷的书签  ·  Android ...·  2 月前    · 
耍酷的书签  ·  安装Numpy | 莫烦Python·  2 月前    · 
Hello NumPy
Hello NumPy

本系列文章希望能讓有興趣學習資料科學 (Data Science) 及 Python 程式語言的人,透過全新不同的方式,由淺入深獲得相關知識,除了前一篇的 Python 初體驗文章,這一篇將帶領大家在未來進入資訊科學領域前,了解如何利用 NumPy 函式庫的強大功能,理解相關基礎應用。

如果想要進一步了解 Python,可以參考 《Python for Beginners》 系列文章 。此系列文章提供給有興趣的讀者一個 淺顯易懂 圖文解說 範例練習 Quiz 測驗 的學習園地,非常適合初學者學習。接下來就讓我們 Hello NumPy!Hello World!

1. NumPy 簡介

NumPy 是 Python 在進行科學運算時,一個非常基礎的套件 (Package),同時也是非常核心的函式庫 (Library),它具有下列幾個重要特色:

>>> import numpy as np
>>> a = np.array([1, 2, 3, 4])     #一維陣列建立
>>> b = np.array([(2.5, 1, 3, 4.5), (5, 6, 7, 8)], dtype = float)  #二維陣列建立
>>> c = np.array([[(2.5, 1, 3, 4.5), (5, 6, 7, 8)], [(2.5, 1, 3, 4.5), (5, 6, 7, 8)]], dtype = float)  #三維陣列建立

下面幾種方式除了可以建立陣列外,也可以同時給予初始值。

>>> np.zeros((2, 3))               # 建立一個2x3全為0的陣列
>>> np.ones((2, 3, 4))             # 建立一個2x3x4全為1的陣列
>>> np.arange(1, 10, 2)            # 建立一個由1開始,不超過10,間隔值為2的均勻數值陣列
>>> np.linspace(0, 10, 5)          # 建立一個0到10之間,均勻的5個數值陣列
>>> np.full((3,2), 8)              # 建立一個3x2全為8的陣列
>>> np.eye(2)                      # 建立一個5x5的單位矩陣
>>> np.random.random((2,3))        # 建立一個2x3的隨機值矩陣

3.2 輸入/輸出 (I/O)

>>> import numpy as np
>>> original_array = np.array([1, 2, 3])
>>> np.save('my_array', original_array)
>>> np.savetxt('my_array.txt', original_array)
>>> array_from_npy = np.load('my_array.npy')
>>> print(array_from_npy)
[1 2 3]
>>> array_from_txtfile = np.loadtxt('my_array.txt')
>>> print(array_from_txtfile)
[1. 2. 3.]

3.3 資料型態 (Data Types)

NumPy 支援比 Python 更多的數字類型。可參考下圖。

NumPy Data Type (圖片來源:kaggle)
NumPy Data Type (圖片來源:kaggle)

其中有 5 種基本數字類型比較常用,分別是 booleans (bool)、integers (int)、unsigned integers (uint)、floating point (float) 和 complex

>>> np.array([1.2, 3, 5.2], dtype='i')
array([1, 3, 5], dtype=int32)
>>> np.array([1, 2, 3], dtype='f')
array([1., 2., 3.], dtype=float32)
>>> x = np.float32(1)
>>> y = np.int_([1.0, 2.3])
array([1, 2])

3.4 陣列查察 (Inspecting Your Array)

>>> a = np.array([1, 2, 3])
>>> b = np.array([(2.5, 1, 4.5), (5, 6, 7, 8)])
>>> a.shape                        # Array dimensions
>>> len(a)                         # Length of array
>>> len(b)                         # Length of array
>>> b.ndim                         # Number of array dimensions
>>> a.size                         # Number of array elements
>>> b.size                         # Number of array elements
>>> b.dtype                        # Data type of array elements
dtype('O')
>>> a.dtype                        # Data type of array elements
dtype('int32')
>>> b.dtype.name                   # Name of data type
'object'
>>> a.dtype.name                   # Name of data type
'int32'
>>> a.astype(float)                # Convert an array to a different type
array([1., 2., 3.])

3.5 尋求幫助 (Asking For Help)

>>> np.info(max)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
>>> np.info(np.ndarray.dtype)
Data-type of the array's elements.
Parameters
----------
Returns
-------
d : numpy dtype object
See Also
--------
numpy.dtype
Examples
--------
array([[0, 1],
       [2, 3]])
>>> x.dtype
dtype('int32')
>>> type(x.dtype)
<type 'numpy.dtype'>

3.6 陣列數學運算 (Array Mathematics)

>>> a = np.array([1, 2, 3])
>>> b = np.array([2, 4, 6])
>>> np.add(a, b)                   # 陣列加法,也可以a + b
array([3, 6, 9])
>>> np.subtract(a, b)              # 陣列減法,也可以a – b
Array([-1, -2, -3])
>>> np.multiply(a, b)              # 陣列乘法,也可以a * b
Array([ 2, 8, 18])
>>> np.divide(a, b)                # 陣列除法,也可以a / b
array([0.5, 0.5, 0.5])

除了四則運算之外,也可以對陣列做其他的算術運算

>>> c = np.array([1, 4, 9])
>>> np.sqrt(c)
array([1., 2., 3.])
>>> np.sin(c)
array([ 0.84147098, -0.7568025 , 0.41211849])
>>> np.cos(c)
array([ 0.54030231, -0.65364362, -0.91113026])
>>> np.log(c)
array([0. , 1.38629436, 2.19722458])
>>> a = np.array([(1, 2, 3), (4, 5, 6)])
>>> b = np.array([(1, 3, 3), (4, 7, 6)])
>>> c = np.array([(1, 2, 3), (4, 5, 6)])
>>> a == b                         # Element-wise comparison
array([[ True, False, True],
 [ True, False, True]])
>>> a < 3                          # Element-wise comparison
array([[ True, True, False],
 [False, False, False]])
>>> np.array_equal(a, b)           # Array-wise comparison
False
>>> a = np.array([2, 5, 7])
>>> b = np.array([(0, 1), (2, 3)])
>>> a.sum()                        # Array-wise sum
>>> a.max()                        # Array-wise maximum value
>>> a.min()                        # Array-wise minimum value
>>> b.max(axis=0)                  # Maximum value of an array row
array([2, 3])
>>> b.max(axis=1)                  # Maximum value of an array row
array([1, 3])
>>> np.median(a)                   # Median
>>> np.mean(a)                     # Mean
4.666666666666667
>>> np.std(a)                      # Standard deviation
2.0548046676563256

3.7 陣列複製與排序 (Copying & Sorting Arrays)

NumPy 同時提供多種陣列間的 copying 及 sorting 功能,我們就先簡介其中幾種做法。

>>> a = np.array([5, 13, -5, -2, 3, 4, 7])
>>> a.sort()
array([-5, -2, 3, 4, 5, 7, 13])
>>> b = np.copy(a)
array([-5, -2, 3, 4, 5, 7, 13])

3.8 子集(Subsetting)、切片(Slicing)、索引(Indexing)

藉由下列範例你將會清楚了解 Subsetting、Slicing Indexing 的應用。我們先試著各建立一個 一維陣列(1D array) 二維陣列(2D array) 如下:

>>> a = np.array([1, 2, 3, 4])
>>> b = np.array([(2.5, 1, 3, 4.5), (5, 6, 7, 8)])
>>> a = np.array([(1, 2), (3, 4)])
>>> b = np.array([(5, 6), (7, 8)])
>>> np.vstack((a, b))              # 垂直方向合併
array([[1, 2],
 [3, 4],
 [5, 6],
 [7, 8]])
>>> np.hstack((a, b))              # 水平方向合併
array([[1, 2, 5, 6],
 [3, 4, 7, 8]])
>>> a = np.array([(1, 2, 3, 4, 5, 6), (-1, -2, -3, -4, -5, -6), (2, 4, 6, 8, 10, 12)])
array([[ 1, 2, 3, 4, 5, 6],
 [-1, -2, -3, -4, -5, -6],
 [ 2, 4, 6, 8, 10, 12]])
>>> np.vsplit(a, 3)                # 垂直方向分割
[array([[1, 2, 3, 4, 5, 6]]), array([[-1, -2, -3, -4, -5, -6]]), array([[ 2, 4, 6, 8, 10, 12]])]
>>> np.hsplit(a, 2)                # 水平方向分割
[array([[ 1, 2, 3],
 [-1, -2, -3],
 [ 2, 4, 6]]), array([[ 4, 5, 6],
 [-4, -5, -6],
 [ 8, 10, 12]])]
>>> np.split(a, 3, axis=0)         # axis=0,沿垂直方向分割
[array([[1, 2, 3, 4, 5, 6]]), array([[-1, -2, -3, -4, -5, -6]]), array([[ 2, 4, 6, 8, 10, 12]])]
>>> np.split(a, 2, axis=1)         # axis=1,沿水平方向分割
[array([[ 1, 2, 3],
 [-1, -2, -3],
 [ 2, 4, 6]]), array([[ 4, 5, 6],
 [-4, -5, -6],
 [ 8, 10, 12]])]