Numpy - 多維數組(上)


加載包: from numpy import *

一、創建numpy數組:

有多種方式:使用 Python 列表或元祖,使用 arange, linspace 等函數,從文件中讀取數據。

1. 列表生成numpy數組


v=array([1,2,3,4])
m=array( [ [1,2],[3,4] ] )
type(v):類型查看,結果爲numpy 模塊提供的 ndarray 類型
v.shape :通過 ndarray.shape 獲得它的維度屬性
v.size :通過ndarray.size獲取數組的元素數量
shape(M),size(M):使用 numpy.shape 與 numpy.size 函數獲取對應屬性值
M.dtype:使用 ndarray 的 dtype 屬性獲得數組元素的類型

numpy.ndarray與list區別:

  • Python 的 list 是動態類型,可以包含不同類型的元素,所以沒有支持諸如點乘等數學函數,因爲要爲 list 實現這些操作會犧牲性能。
  • Numpy 數組是靜態類型並且齊次。 元素類型在數組創建的時候就已經確定了。
  • Numpy 數組節約內存。
  • 由於是靜態類型,對其數學操作函數(如矩陣乘法,矩陣加法)的實現可以使用 C 或者 Fortran 完成。

M = array([[1, 2], [3, 4]], dtype=complex) :通過在創建數組時使用 dtype 關鍵字參數顯示地定義元素類型。dtype 的常用值有:int, float, complex, bool, object 等,大小比如:int64/16, float128, complex128

2. 使用函數來生成數組

需要生產大數組時可以使用函數來生成數組,最常用的有如下幾個函數:

  • arange
    x = arange(0, 10, 1) #arguments: start, stop, step
    => array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

  • linspace 與 logspace
    linspace(0, 10, 25):# using linspace, both end points ARE included 生成25個0~10的數
    logspace(0, 10, 10, base=e) 加對數生成10個數

  • mgrid
    x, y = mgrid[0:5, 0:5]:# similar to meshgrid in MATLAB 生成網格數據
    x爲每行元素相同,按行從0~4遞增
    y爲每列元素相同,按列從0~4遞增

  • random data
    from numpy import random:導入
    random.rand(5,5): uniform random numbers in [0,1]
    random.randn(5,5):standard normal distributed random numbers

  • diag
    diag([1,2,3]): a diagonal matrix
    => array([[1, 0, 0],
    [0, 2, 0],
    [0, 0, 3]])
    diag([1,2,3], k=1) : diagonal with offset from the main diagonal
    => array([[0, 1, 0, 0],
    [0, 0, 2, 0],
    [0, 0, 0, 3],
    [0, 0, 0, 0]])

  • zeros 與 ones
    zeros((3,3))
    ones((3,3))

3. 文件 I/O 創建數組

  • CSV
    CSV是一種常用的數據格式化文件類型,從中讀取數據使用numpy.genfromtxt 函數。
    data = genfromtxt(‘stockholm_td_adj.dat’) 讀數據head stockholm_td_adj.dat,data爲numpy 數組。
    savetxt(“random-matrix.csv”, M,fmt=’%.5f’):使用 numpy.savetxt 將 Numpy 數組保存到csv文件中。 # fmt specifies the format
    !cat random-matrix.csv:查看文件。

  • Numpy 原生文件類型
    使用 numpy.save 與 numpy.load 保存和讀取:
    save(“random-matrix.npy”, M)
    load(“random-matrix.npy”)

  • numpy 數組的常用屬性
    M.itemsize //bytes per element
    M.nbytes //number of bytes
    M.ndim //number of dimensions

    4. 操作數組

  • 索引
    v[0],M[1,1]:用方括號進行檢索
    如果是N(N > 1)維數列,在檢索時省略了一個索引值則會返回一整行((N-1)維數列),例:

M
=> array([[ 0.70506801, 0.54618952, 0.31039856],
[ 0.26640475, 0.10358152, 0.73231132],
[ 0.07987128, 0.34462854, 0.91114433]])
M[1]
=> array([ 0.26640475, 0.10358152, 0.73231132])

使用 : 能達到同樣的效果:

M[1,:] # row 1
=> array([ 0.26640475, 0.10358152, 0.73231132])
M[:,1] # column 1
=> array([ 0.54618952, 0.10358152, 0.34462854])

可以利用索引進行賦值:M[1,:] = 0,M[:,2] = -1

  • 切片索引
    M[lower:upper:step]:A[1:3]取下標1到3,不包括3.
    進行切片賦值時,原數組會被修改。參數可任意省略:
    A[::] 輸出所有元素
    負值索引從數組尾開始計算:A[-3:] # the last three elements
    索引切片在多維數組的應用也是一樣的:

A = array([[n+m*10 for n in range(5)] for m in range(5)])
=>array([[ 0, 1, 2, 3, 4],
[10, 11, 12, 13, 14],
[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34],
[40, 41, 42, 43, 44]])

  • 高級索引
    指使用列表或者數組進行索引:

row_indices = [1, 2, 3]
A[row_indices]
=> array([[10, 11, 12,13, 14],
[20, 21, 22, 23, 24],
[30, 31, 32, 33, 34]])
col_indices = [1, 2, -1] # remember, index -1 means the last element
A[row_indices,col_indices]
=> array([11, 22, 34])


可以用索引掩碼:

B = array([n for n in range(5)])
B
=> array([0, 1, 2, 3, 4])

row_mask = array([True, False, True, False, False])
B[row_mask]
=> array([0, 2])

row_mask = array([1,0,1,0,0], dtype=bool)
B[row_mask]


使用比較操作符生成掩碼:

x = arange(0, 10, 0.5)
x
=> array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. ,
5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5])

mask = (5 < x) * (x < 7.5)
mask
=> array([False, False, False, False, False, False, False, False, False,
False, False, True, True, True, True, False, False, False,
False, False], dtype=bool)

x[mask]
=> array([ 5.5, 6. , 6.5, 7. ])

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