numpy---(上)

Numpy

Numpy ndarray

N維數組對象ndarray, 是一系列同類型數據的集合, 索引以0下標開始, 建立一個ndarray對象, 需調用array函數:python

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
名稱 描述
object 數組或嵌套的數列
dtype 數組元素的數據類型, 可選, 默認爲None
copy 是否須要複製, 可選, 默認爲True
order 建立數組的樣式, C爲行方向, F爲列方向, A爲任意方向(默認), 默認爲None
subok 默認返回一個與基類類型一致的數組, 默認爲False
ndmin 指定生成數組的最小維度, 默認爲0

實例

import numpy as np
a = np.array([1, 2, 3])
print(a)    # [1 2 3]

# 多一個維度
a1 = np.array([[1, 2],[3, 4]])
print(a1)   
# [[1 2]
#   [3 4]]

# 最小維度
a2 = np.array([1,2, 3, 4, 5], ndmin=2)
print(a2)   # [[1 2 3 4 5]]

# dtype參數
a3 = np.array([1, 2, 3], dtype=complex)
print(a3)   # [1.+0.j 2.+0.j 3.+0.j]

數據類型

  • numpy支持的數據類型比python內置的數據類型多不少, 基本上能夠和C語言的數據類型對應上.
  • numpy的數值類型其實是dtype對象的實例, 並對應惟一的字符, np.int32, np.float32等.

數據類型對象(dtype)

  • 數據類型對象是用來描述與數組對象的內存區如何使用, 依賴於數組的類型, 數據的大小, 數據的字節順序, 結構化類型下字段的名稱等等.
  • 字節順序是經過對數據預先設定'<'或'>'來決定的, '<'意味着小端法, 即最小值存儲在最小的地址, 即低位在最前面; '>'意味着大端法, 即高位放在前面.
num.dtype(object, align, copy)

# object 要轉換爲的數據類型對象
# align  若爲true時, 填充字段使其爲相似C的結構體
# copy   複製dtype對象, 若爲false, 則是對內置函數類型對象的引用
  • 每一個內建類型都對應一個惟必定義的字符代碼
字符 對應類型
b 布爾型
i 有符號整型
u 無符號整型
f 浮點型
c 複數浮點型
m timedelta 時間間隔
M datetime 日期時間
O python對象
S,a byte字符串
U Unicode
V 原始數據 void

實例

# 使用標量類型
dt = np.dtype(np.int32)
print(dt)
# int32

# int8, int16, int32, int64四種數據類型可使用字符串'i1', 'i2', 'i3', 'i4'代替
dt1 = np.dtype('i4')
print(dt1)
# int32

# 字節順序標註
dt2 = np.dtype('<i4')
print(dt2)
# int32


# 結構化數據類型的使用, 類型字段和對應的實際類型被建立
dt3 = np.dtype([('age', np.int8)])
print(dt3)
# [('age', 'i1')]


# 將數據類型應用於ndarray對象
dt4 = np.dtype([('age', np.int8)])
a4 = np.array([(10,), (20,),(30,)], dtype=dt4)
print(a4)
# [(10,) (20,) (30,)]

print(a4.dtype)
# [('age', 'i1')]


# 類型字段名能夠用於存取實際的age列
dt5 = np.dtype([('age', np.int8)])
a5 = np.array([(10,), (20,),(30,)], dtype=dt4)
print(a5['age'])
# [10 20 30]


# 定義一個結構化數據類型student, 包含字符串字段name, 整數字段age, 及浮點子彈marks, 並將這個dtype應用到ndarray對象
student = np.dtype([('name', 'S20'), ('age', 'i1'), ('marks', 'f4')])
a6 = np.array([('abc', 21, 50), ('xyz', 18, 75)], dtype=student)
print(student)
print(a6)

# [('name', 'S20'), ('age', 'i1'), ('marks', '<f4')]
# [(b'abc', 21, 50.) (b'xyz', 18, 75.)]

數組屬性

  • 數組的維數爲秩, 一維數組的秩爲1, 二維數組的秩爲2.
  • 每個線性的數組稱爲是一個軸(axis), 也就是維度(dimensions), 而軸的數量---秩, 就是數組的維數.
  • axis=0, 表示沿着第0軸進行操做, 即對每一個列進行操做;axis=1, 表示沿着第1軸進行操做, 即對每一個行進行操做.
屬性 說明
ndarray.ndim 秩, 軸的數量或者維度的數量
ndarray.shape 數組的維度, 返回一個元組, 對於矩陣, n行m列,
ndarray.size 數組元素的總個數, n*m
ndarray.dtype 元素類型
ndarray.itemsize 每一個元素的大小, 以字節爲單位
ndarray.flags 內存信息
ndarray.real 實部
ndarray.imag 虛部
ndarray.data 數組元素的緩衝區(通常經過數組的索引獲取元素, 一般這個屬性不經常使用)

建立數組

numpy.empty

  • 用來建立一個指定形狀(shape)、數據類型(dtype)且未初始化的數組
numpy.empty(shape, dtype = float, order = 'C')

# shape 數組形狀
# dtype 數據類型, 可選
# order 有'C'和'F'兩個選項, 分別表示行優先, 和列優先, 在內存中存儲元素的順序
x1 = np.empty([3, 2], dtype=int)
# 數組元素爲隨機值, 由於未初始化
print(x1)
'''
[[       848          0]
 [       848          0]
 [-997652816        182]]
 '''

numpy.zeros

  • 建立指定大小的數組, 數組元素以0來填充
numpy.zeros(shape, dtype = float, order = 'C')
# 默認爲浮點數
x2 = np.zeros(5)
print(x2)
# [0. 0. 0. 0. 0.]


# 設置爲整數
x3 = np.zeros((5,), dtype=np.int)
print(x3)
# [0 0 0 0 0]

# 自定義類型
x3 = np.zeros((2,2), dtype=[('x','i4'), ('y','i4')])
print(x3)
'''
[[(0, 0) (0, 0)]
[(0, 0) (0, 0)]]
'''

numpy.ones

numpy.ones(shape, dtype = None, order = 'C')
# 默認爲浮點數
x4 = np.ones(5)
print(x4)
# [1. 1. 1. 1. 1.]


# 設置爲整型
x4 = np.ones([2, 2], dtype=np.int)
print(x4)
'''
[[1 1]
 [1 1]]
'''

從已有的數組建立數組

numpy.asarray

numpy.asarray(a, dtype = None, order = None)

# a 任意形式的輸入參數, 列表, 列表的元組, 元組, 元組的元組, 元組的列表, 多維數組
# dtype  數據類型, 可選
# order  可選, 有C和F兩個選項, 行優先和列優先
# 將列表轉換爲ndarray
lst1 = [1, 2, 3]
x6 = np.asarray(lst1)
print(x6)
# [1 2 3]


# 將元組轉換爲ndarray
t1 = (1, 2, 3)
x7 = np.asarray(t1)
print(x7)


# 將元組轉換爲ndarray
t1 = (1, 2, 3)
x7 = np.asarray(t1)
print(x7)
# [1 2 3]


# 將元組的列表轉換爲ndarray
lst2 = [(1, 2, 3), (4, 5)]
x8 = np.asarray(lst2)
print(x8)
# [(1, 2, 3) (4, 5)]


# 設置dtype參數
x9 = np.asarray(lst1, dtype=float)
print(x9)
# [1. 2. 3.]

numpy.frombuffer

  • 用於實現動態數組, 接受buffer輸入參數, 以流的形式讀入轉化成ndarray對象.
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

# 注意: buffer是字符串時, 要轉成bytes, 即在原字符串前加上b.
參數 描述
buffer 任意對象, 會以流的形式讀入
dtype 返回數組的數據類型, 可選
count 讀取的數據數量, 默認爲-1, 讀取全部的數據
offset 讀取的起始位置, 默認爲0
s = b'hello world'
a10 = np.frombuffer(s, dtype='S1')
print(a10)

'''
[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd']
'''

numpy.fromiter

  • 從可迭代對象中創建ndarray對象, 返回一維數組.
numpy.fromiter(iterable, dtype, count=-1)
list2 = range(5)
# it = iter(list2)
a11 = np.fromiter(list2, dtype=float)
print(a11)

# [0. 1. 2. 3. 4.]

從數值範圍建立數組

numpy.arange

  • 建立數值範圍並返回ndarray對象
numpy.arange(start, stop, step, dtype)

# 起始值, 默認爲0
# 終止值, 不包含
# 步長, 默認爲1
# 返回ndarray的數據類型, 若是沒有提供, 則使用輸入數據的類型
x11 = np.arange(6)
print(x11)
# [0 1 2 3 4 5]


# 設置返回類型爲float
x12 = np.arange(6, dtype=float)
print(x12)
# [0. 1. 2. 3. 4. 5.]


# 設置起始值, 終止值及步長
x13 = np.arange(10, 20, 2)
print(x13)
# [10 12 14 16 18]

numpy.linspace

  • 用於建立一個一維數組, 數組是一個等差數列構成的
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
參數 描述
start 序列的起始值
stop 序列的終止值
num 要生成的等差數列的樣本的數量, 默認爲50
endpoint 爲True時, 數列中包含stop值, 反之不包含, 默認爲True
retstep 爲True時, 生成的數組會顯示間距, 反之不顯示
dtype ndarray的數據類型
b1 = np.linspace(1, 10, 10)
print(b1)
# [ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]


# 設置元素所有是1的等差數列
b2 = np.linspace(1, 1, 10)
print(b2)
# [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]


# 設置endpoint爲False, 不包含終止值
b3 = np.linspace(10, 20, 5, endpoint=False)
print(b3)
# [10. 12. 14. 16. 18.]


# 設置間距
b4 = np.linspace(1, 10, 10, retstep=True)
print(b4)
# (array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.]), 1.0)


# 擴展
b5 = np.linspace(1, 10, 10).reshape(10, 1)
print(b5)
'''
[[ 1.]
 [ 2.]
 [ 3.]
 [ 4.]
 [ 5.]
 [ 6.]
 [ 7.]
 [ 8.]
 [ 9.]
 [10.]]
'''

numpy.logspace

  • 用於建立一個等比數列
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
參數 描述
start 序列的起始值: base ** start
stop 序列的終止值: base ** stop
num 要生成的等步長的樣本的數量值, 默認爲50
endpoint 爲true時, 數列中包含stop值, 反之不包含
base 對數log的底數
dtype ndarray的數據類型
# 默認底數是10
b6 = np.logspace(1.0, 2.0, num=10)
print(b6)
'''
[ 10.          12.91549665  16.68100537  21.5443469   27.82559402
  35.93813664  46.41588834  59.94842503  77.42636827 100.        ]
'''


# 將底數設置爲2
b7 = np.logspace(0, 9, 10, base=2)
print(b7)
'''
[  1.   2.   4.   8.  16.  32.  64. 128. 256. 512.]
'''

切片和索引

  • 經過索引和切片訪問和修改ndarray對象的內容, 索引下標從0開始, 切片對象經過內置函數slice設置start, stop及step參數, 從而切割出一個新數組,數組

  • 也能夠經過冒號分隔切片參數 start: stop: step來進行切片操做函數

b8 = np.arange(10)
s1 = slice(2, 7, 2)
print(b8[s1])
# [2 4 6]

print(b8[2:7:2])
# [2 4 6]

print(b8[5])
# 5

print(b8[2:])
# [2 3 4 5 6 7 8 9]

print(b8[2:5])
# [2 3 4]
  • 多維數組一樣適用上述索引提取方法
a20 = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])
print(a20)
print('從數組索引 a20[1:] 處開始切割')
print(a20[1:])

'''
[[1 2 3]
 [3 4 5]
 [4 5 6]]
從數組索引 a20[1:] 處開始切割
[[3 4 5]
 [4 5 6]]
'''
  • 切片還能夠包括省略號..., 來使選擇元組的長度與數組的維度相同.
print(a20[..., 1])
[2 4 5]

print(a20[1, ...])
print('*' * 20)
print(a20[..., 1:])
'''
[3 4 5]
********************
[[2 3]
 [4 5]
 [5 6]]
'''

高級索引

整數數組索引

# 獲取數據中(0, 0), (1, 1)和(2, 0)位置處的元素
x20 = np.array([[1, 2], [3, 4], [5, 6]])
y20 = x20[[0, 1, 2], [0, 1, 0]]
print(y20)
# [1 4 5]


x21 = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
print('數組爲:\n{}\n'.format(x21))

rows = np.array([[0, 0], [3, 3]])
cols = np.array([[0, 2], [0, 2]])
y21 = x21[rows, cols]
print('這個數組的四個角元素:\n{}'.format(y21))


'''
數組爲:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

這個數組的四個角元素:
[[ 0  2]
 [ 9 11]]
'''


a0 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b0 = a0[1:3, 1:3]
c0 = a0[1:3, [1, 2]]
d0 = a0[..., 1:]
print(a0)
print('*' * 30)
print(b0)
print('*' * 30)
print(c0)
print('*' * 30)
print(d0)

'''
[[1 2 3]
 [4 5 6]
 [7 8 9]]
******************************
[[5 6]
 [8 9]]
******************************
[[5 6]
 [8 9]]
******************************
[[2 3]
 [5 6]
 [8 9]]
'''

布爾索引

  • 經過一個布爾數組來索引目標數組.
# 獲取大於5的元素
print(x21[x21 > 5])
# [ 6  7  8  9 10 11]


# 使用 ~ 取補運算符來過濾NaN
a20 = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
print(a20)
print(a20[~np.isnan(a20)])
'''
[nan  1.  2. nan  3.  4.  5.]
[1. 2. 3. 4. 5.]
'''


a21 = np.array([1, 2+6j, 5, 3.5+5j])
print(a21[np.iscomplex(a21)])
# [2. +6.j 3.5+5.j]

花式索引

  • 利用整數數組進行索引, 根據索引數組的值做爲目標數組某個軸的下標來取值.
  • 若是使用一維整型數組做爲索引, 且目標數組也是一維數組, 索引的結果就是對應位置的元素; 若是目標數組是二維數組, 那就是對應下標的行.
  • 花式索引是將數據複製到新數組中.
# 傳入順序索引數組
import numpy as np
x31 = np.arange(32).reshape(8, 4)
print(x31)
print('-' * 20)
print(x31[[4, 2, 1, 7]])
'''
[[ 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 27]
 [28 29 30 31]]
--------------------
[[16 17 18 19]
 [ 8  9 10 11]
 [ 4  5  6  7]
 [28 29 30 31]]
'''

# 傳入倒序索引數組
print(x31[[-4, -2, -1, -7]])
'''
[[16 17 18 19]
 [24 25 26 27]
 [28 29 30 31]
 [ 4  5  6  7]]
'''


# 傳入多個索引數組, 使用np.ix_
print(x31[np.ix_([1, 5, 7, 2],[0, 3, 1, 2])])
'''
[[ 4  7  5  6]
 [20 23 21 22]
 [28 31 29 30]
 [ 8 11  9 10]]
'''
相關文章
相關標籤/搜索