陣列入門

NumPy 入門

Izzy Weber

Core Curriculum Manager, DataCamp

NumPy 與 Python 生態系

Atlas 托舉地球的圖像,設計為 NumPy 樣式,象徵 NumPy 撐起 Python 世界

NumPy 入門

NumPy 陣列

 

1D、2D、3D 陣列圖示

NumPy 入門

匯入 NumPy

 

import numpy as np
NumPy 入門

以清單建立 1D 陣列

python_list = [3, 2, 5, 8, 4, 9, 7, 6, 1]
array = np.array(python_list)
array
array([3, 2, 5, 8, 4, 9, 7, 6, 1])

 

type(array)
numpy.ndarray
NumPy 入門

以清單建立 2D 陣列

python_list_of_lists = [[3, 2, 5],
                        [9, 7, 1],
                        [4, 3, 6]]
np.array(python_list_of_lists)
array([[3, 2, 5],
       [9, 7, 1],
       [4, 3, 6]])
NumPy 入門

Python 清單

  • 可包含多種不同資料型別
python_list = ["beep", False, 56, .945, [3, 2, 5]]

 

NumPy 陣列

  • 僅能包含單一資料型別
  • 佔用較少記憶體空間
numpy_boolean_array = [[True, False], [True, True], [False, True]]

numpy_float_array = [1.9, 5.4, 8.8, 3.6, 3.2]
NumPy 入門

從零建立陣列

 

有許多 NumPy 函式可從零建立陣列,例如:

  • np.zeros()
  • np.random.random()
  • np.arange()
NumPy 入門

建立陣列:np.zeros()

np.zeros((5, 3))
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
NumPy 入門

建立陣列:np.random.random()

np.random.random((2, 4))
array([[0.88524516, 0.85641352, 0.33463107, 0.53337117],
       [0.69933362, 0.09295327, 0.93616428, 0.03601592]])

 

np.random 是一個 NumPy 模組,而 np.random.random() 是 np.random 裡的函式

NumPy 入門

使用 np.arange() 建立陣列

np.arange(-3, 4)
array([-3, -2, -1,  0,  1,  2,  3])
np.arange(4)
array([0, 1, 2, 3])
np.arange(-3, 4, 3)
array([-3,  0,  3])
from matplotlib import pyplot as plt
plt.scatter(np.arange(0, 7),
            np.arange(-3, 4))
plt.show()

X 與 Y 軸各為一個 range 陣列的散佈圖

NumPy 入門

一起來練習吧!

NumPy 入門

Preparing Video For Download...