天天看點

NumPy Beginner's Guide 2e 帶注釋源碼 二、NumPy 基礎入門

版權聲明:License CC BY-NC-SA 4.0 https://blog.csdn.net/wizardforcel/article/details/72823633

# 來源:NumPy Biginner's Guide 2e ch2
>>> from numpy import *
           

多元數組

# 建立多元數組
>>> m = array([arange(2), arange(2)])
>>> m
array([[0, 1],
       [0, 1]])
# 列印形狀
>>> m.shape
(2, 2)

# 建立 2x2 的矩陣
>>> a = array([[1,2],[3,4]])
>>> a
array([[1, 2],
       [3, 4]])
       
# 讀取矩陣的每個元素
>>> a[0,0]
1
>>> a[0,1]
2
>>> a[1,0]
3
>>> a[1,1]
4
           

數值類型

類型 描述

bool

布爾值,一位

int

平台相關整數,

int32

int64

int8

位元組(

-128 ~ 127

int16

整數(

-32768 ~ 32767

int32

-2 ** 31 ~ 2 ** 31 - 1

int64

-2 ** 63 ~ 2 ** 63 - 1

uint8

無符号整數(

0 ~ 255

uint16

0 ~ 65535

uint32

0 ~ 2 ** 32 - 1

uint64

0 ~ 2 ** 64 - 1

float16

半精度浮點,符号位,5 位指數,10 位尾數

float32

單精度浮點,符号位,8 位指數,23 位尾數

float64

float

雙精度浮點,符号位,11 位指數,52 位尾數

complex64

複數,由兩個 32 位浮點表示(實部和虛部)

complex128

complex

複數,由兩個 64 位浮點表示(實部和虛部)
# 每個資料類型都可用作轉換函數
>>> float64(42)
42.0
>>> int8(42.0)
42
>>> bool(42)
True
>>> bool(0)
False
>>> bool(42.0)
True
>>> float(True)
1.0
>>> float(False)
0.0

# 複數轉整數會抛出錯誤
>>> int(42.0 + 1.j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to int
           

資料類型對象(dtype)

# 從數值類型構造
>>> dtype(float)
dtype('float64')

# 從字元代碼構造
>>> dtype('f')
dtype('float32')
>>> dtype('d')
dtype('float64')

# 從雙字元代碼構造
>>> dtype('f8')
dtype('float64')

# 擷取所有字元代碼
>>> sctypeDict.keys()
[0, … 'i2', 'int0']
 
# char 屬性擷取字元代碼
>>> t = dtype('Float64')
>>> t.char
'd'

# type 屬性擷取類型
>>> t.type
<type 'numpy.float64'>

# str 屬性擷取完整字元串表示
# 第一個字元是位元組序,< 表示小端,> 表示大端,| 表示平台的位元組序
>>> t.str
'<f8'

# 擷取大小
>>> t.itemsize
8

# 許多函數擁有 dtype 參數
# 傳入數值類型、字元代碼和 dtype 都可以
>>> arange(7, dtype=uint16)
array([0, 1, 2, 3, 4, 5, 6], dtype=uint16)
           
字元代碼

bool

?

,

b1

int8

b

i1

uint8

B

u1

int16

h

i2

uint16

H

u2

int32

i

i4

uint32

I

u4

int64

q

i8

uint64

Q

u8

float16

f2

e

float32

f4

f

float64

f8

d

complex64

F4

F

complex128

F8

D

str

S

(可以在

S

後面添加數字,表示字元串長度,比如

S3

表示長度為三的字元串,不寫則為最大長度)

unicode

U

object

O

void

V

記錄類型

# 定義記錄類型
# dtype 傳入字段清單,字段用名稱和類型表示
>>> t = dtype([('name', str_, 40), ('numitems', int32), ('price', float32)])
>>> t
dtype([('name', '|S40'), ('numitems', '<i4'), ('price','<f4')])

# 擷取字段
>>> t['name']
dtype('|S40')

# 使用記錄類型建立數組
# 否則它會把記錄拆開
>>> itemz = array([('Meaning of life DVD', 42, 3.14), ('Butter', 13,2.72)], dtype=t)
>>> itemz[1]
('Butter', 13, 2.7200000286102295)
           

操作形狀

>>> b = array([[[ 0,  1,  2,  3],
                [ 4,  5,  6,  7],
                [ 8,  9, 10, 11]],
               [[12, 13, 14, 15],
                [16, 17, 18, 19],
                [20, 21, 22, 23]]])

# ravel 将數組展開,建立視圖
>>> b.ravel()
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13,14, 15, 16,
       17, 18, 19, 20, 21, 22, 23])

# flatten 将數組展開,建立副本
>>> b.flatten()
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13,14, 15, 16,
       17, 18, 19, 20, 21, 22, 23])
       
# reshape 用于設定數組形狀
# 總數必須一緻
>>> b.shape = (6,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])

# 用于轉置矩陣
>>> b.transpose()
array([[ 0,  4,  8, 12, 16, 20],
       [ 1,  5,  9, 13, 17, 21],
       [ 2,  6, 10, 14, 18, 22],
       [ 3,  7, 11, 15, 19, 23]])

# resize 用于原地設定形狀
# 其它和 reshape 相同
>>> b.resize((2,12))
>>> b
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
           

堆疊

>>> a = arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> b = 2 * a
>>> b
array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])
       
# 二維數組的軸
# 0:豎直,1:水準
# 三維數組的軸
# 0:縱深,1:豎直,2:水準
       
# 水準堆疊
>>> hstack((a, b))
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]])
# 也可以使用 concatenate,指定軸 1(二維數組的水準軸)
>>> concatenate((a, b), axis=1)
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]])
       
# 豎直堆疊
>>> vstack((a, b))
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])
# 也可以使用 concatenate,指定軸 0(二維數組的數值軸,預設值)
>>> concatenate((a, b), axis=0)
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])

# 縱深堆疊
# 沿第三個軸(深度)堆疊
>>> dstack((a, b))
array([[[ 0,  0],
        [ 1,  2],
        [ 2,  4]],
       [[ 3,  6],
        [ 4,  8],
        [ 5, 10]],
       [[ 6, 12],
        [ 7, 14],
        [ 8, 16]]])

# 按列堆疊
# 對于一維數組,column_stack 使一維數組變成二維數組的列
>>> oned = arange(2)
>>> oned
array([0, 1])
>>> twice_oned = 2 * oned
>>> twice_oned
array([0, 2])
>>> column_stack((oned, twice_oned))
array([[0, 0],
       [1, 2]])
# 對于二維數組,就是 hstack
>>> column_stack((a, b))
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]])
>>> column_stack((a, b)) == hstack((a, b))
array([[ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True]], dtype=bool)
       
# 按行堆疊
# 對于一維數組,row_stack 使一維數組變成二維數組的行
>>> row_stack((oned, twice_oned))
array([[0, 1],
       [0, 2]])
# 對于二維數組,就是 vstack
>>> row_stack((a, b))
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])
>>> row_stack((a,b)) == vstack((a, b))
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)
           

分割

>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
       
# 水準分割,指明分割為多少塊
# 不能均分時報錯
>>> hsplit(a, 3)
[array([[0],
       [3],
       [6]]),
 array([[1],
       [4],
       [7]]),
 array([[2],
       [5],
       [8]])]
# 也可以使用 split 函數指定軸 1(二維數組的水準軸)
>>> split(a, 3, axis=1)
[array([[0],
       [3],
       [6]]),
 array([[1],
       [4],
       [7]]),
 array([[2],
       [5],
       [8]])]
# 豎直分割,指明分割為多少塊
# 不能均分時報錯
>>> vsplit(a, 3)
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7,8]])]
# 也可以使用 split 函數指定軸 0(二維數組的豎直軸)
>>> split(a, 3, axis=0)
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7,8]])]

# 縱深分割
# 我們需要一個三維數組
>>> c = arange(27).reshape(3, 3, 3)
>>> c
array([[[ 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]]])
>>> dsplit(c, 3)
[array([[[ 0],
        [ 3],
        [ 6]],
       [[ 9],
        [12],
        [15]],
       [[18],
        [21],
        [24]]]),
 array([[[ 1],
        [ 4],
        [ 7]],
       [[10],
        [13],
        [16]],
       [[19],
        [22],
        [25]]]),
 array([[[ 2],
        [ 5],
        [ 8]],
       [[11],
        [14],
        [17]],
       [[20],
        [23],
        [26]]])]


           

屬性

# ndim 擷取數組次元
>>> b
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
>>> b.ndim
2

# size 擷取元素數量
>>> b.size
24

# itemsize 擷取元素大小
>>> b.itemsize
8

# 這兩個乘起來就是數組的大小 nbytes
>>> b.nbytes
192
>>> b.size * b.itemsize
192

# T 屬性用于擷取轉置,和 tranpose 函數一樣
>>> b.resize(6,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])
>>> b.T
array([[ 0,  4,  8, 12, 16, 20],
       [ 1,  5,  9, 13, 17, 21],
       [ 2,  6, 10, 14, 18, 22],
       [ 3,  7, 11, 15, 19, 23]])
       
# 但如果數組是一維的,我們隻能得到它的視圖
>>> b.ndim
1
>>> b.T
array([0, 1, 2, 3, 4])

# NumPy 中的複數用 j 表示
>>> b = array([1.j + 1, 2.j + 3])
>>> b
array([ 1.+1.j,  3.+2.j])
>>> b.dtype
dtype('complex128')
>>> b.dtype.str
'<c16'

# real 用于擷取實部
>>> b.real
array([ 1.,  3.])

# imag 用于擷取虛部
>>> b.imag
array([ 1.,  2.])

# flat 屬性擷取 numpy.flatiter 對象,它是一個疊代器,用于周遊所有元素
>>> b = arange(4).reshape(2,2)
>>> b
array([[0, 1],
       [2, 3]])
>>> f = b.flat
>>> f
<numpy.flatiter object at 0x103013e00>
>>> for item in f: print item
0
1
2
3

# 也可以直接索引 flatiter 對象
>>> b.flat[2]
2

# 或者多個元素
>>> b.flat[[1,3]]
array([1, 3])

# flat 屬性是可設定的,修改 flat 屬性的值會修改原始數組
# 設定所有元素
>>> b.flat = 7
>>> b
array([[7, 7],
       [7, 7]])
# 或者僅僅設定某個元素
>>> b.flat[[1,3]] = 1
>>> b
array([[7, 1],
       [7, 1]])
           

轉換

# 轉換為 Python 清單
>>> b
array([ 1.+1.j,  3.+2.j])
>>> b.tolist()
[(1+1j), (3+2j)]

# astype 轉換數組中的元素類型
# 複數轉為整數時會丢掉虛部
>>> b
array([ 1.+1.j,  3.+2.j])
>>> b.astype(int)
/usr/local/bin/ipython:1: ComplexWarning: Casting complex values to real discards the imaginary part
  #!/usr/bin/python
array([1, 3])