NumPy學習筆記——創建數組

NumPy創建數組

創建方法概述

官方文檔鏈接

ones和zeros填充方式

方法 描述
empty(shape[, dtype, order]) 返回給定形狀和類型的新數組,元素是隨機的
empty_like(prototype[, dtype, order, subok, …]) 返回形狀和類型與給定數組相同的新數組,元素是隨機的
eye(N[, M, k, dtype, order]) 返回一個二維數組,對角線上有一個,其他地方爲零。
identity(n[, dtype]) 返回單位矩陣
ones(shape[, dtype, order]) 返回給定形狀和類型的新數組,並填充爲1。
ones_like(a[, dtype, order, subok, shape]) 返回形狀與類型與給定數組相同的數組。
zeros(shape[, dtype, order]) 返回給定形狀和類型的新數組,並用零填充。
zeros_like(a[, dtype, order, subok, shape]) 返回形狀與類型與給定數組相同的零數組。
full(shape, fill_value[, dtype, order]) 返回給定形狀和類型的新數組,並用fill_value填充。
full_like(a, fill_value[, dtype, order, …]) 返回形狀和類型與給定數組相同的完整數組。

從現有數據創建

方法 描述
array(object[, dtype, copy, order, subok, ndmin]) 創建一個數組。
asarraya[, dtype, order]) 將輸入轉換爲數組。
asanyarray(a[, dtype, order]) 將輸入轉換爲ndarray,但通過ndarray子類。
ascontiguousarray(a[, dtype]) 返回內存中的連續數組(ndim > = 1)(C順序)。
asmatrix(data[, dtype]) 將輸入解釋爲矩陣。
copy(a[, order]) 返回給定對象的數組副本。
frombuffer(buffer[, dtype, count, offset]) 將緩衝區解釋爲一維數組。
fromfile(file[, dtype, count, sep, offset]) 根據文本或二進制文件中的數據構造一個數組。
fromfunction(function, shape, **kwargs) 通過在每個座標上執行一個函數來構造一個數組。
fromiter(iterable, dtype[, count]) 從可迭代對象創建一個新的一維數組。
fromstring(string[, dtype, count, sep]) 從字符串中的文本數據初始化的新一維數組。
loadtxt(fname[, dtype, comments, delimiter, …]) 從文本文件加載數據。

創建記錄數組

方法 描述
core.records.array(obj[, dtype, shape, …]) 從各種各樣的對象構造一個記錄數組。
core.records.fromarrays(arrayList[, dtype, …]) 從(平面)數組列表創建記錄數組
core.records.fromrecords(recList[, dtype, …]) 從文本格式的記錄列表創建一個rearray
core.records.fromstring(datastring[, dtype, …]) 根據字符串中包含的二進制數據創建(只讀)記錄數組
core.records.fromfile(fd[, dtype, shape, …]) 根據二進制文件數據創建數組

創建字符數組

方法 描述
core.defchararray.array(obj[, itemsize, …]) 創建一個chararray。
core.defchararray.asarray(obj[, itemsize, …]) 將輸入轉換爲chararray,僅在必要時複製數據。

數值範圍

方法 描述
arange([start,] stop[, step,][, dtype]) 返回給定間隔內的均勻間隔的值。
linspace(start, stop[, num, endpoint, …]) 返回指定間隔內的等間隔數字。
logspace(start, stop[, num, endpoint, base, …]) 返回數以對數刻度均勻分佈。
geomspace(start, stop[, num, endpoint, …]) 返回數字以對數刻度(幾何級數)均勻分佈。
meshgrid(*xi, **kwargs) 從座標向量返回座標矩陣。
mgrid nd_grid實例,它返回一個密集的多維“ meshgrid”。
ogrid nd_grid實例,它返回一個開放的多維“ meshgrid”。

創建矩陣

方法 描述
diag(v[, k]) 提取對角線或構造對角線數組。
diagflat(v[, k]) 使用展平的輸入作爲對角線創建二維數組。
tri(N[, M, k, dtype]) 在給定對角線處及以下且在其他位置爲零的數組。
tril(m[, k]) 數組的下三角。
triu(m[, k]) 數組的上三角。
vander(x[, N, increasing]) 生成範德蒙矩陣。

矩陣類

方法 描述
mat(data[, dtype]) 將輸入解釋爲矩陣。
bmat(obj[, ldict, gdict]) 從字符串,嵌套序列或數組構建矩陣對象。

常用的數組創建方法

使用底層的ndarray構造器來創建

ndarray(shape, dtype=None, buffer=None, offset=0, strides=None, order=None)

參數說明:

參數 類型 描述
shape int型tuple 多維數組的形狀
dtype data-type 數組中元素的類型,可選
buffer 用於初始化數組的buffer
offset int buffer中用於初始化數組的首個數據的偏移
strides int型tuple 每個軸的下標增加1時,數據指針在內存中增加的字節數
order ‘C’ 或者 ‘F’ ‘C’:行優先;‘F’:列優先

示例:

a = np.ndarray((2, 3), dtype=int, buffer=np.array([1, 2, 3, 4, 5, 6]), offset=0, order='C')
print(a)							# output:[[1 2 3],[4 5 6]]
a = np.ndarray(shape=(2,3), dtype=int, buffer=np.array([1, 2, 3, 4, 5, 6, 7]), offset=0, order="F")
print(a)							# output:[[1 3 5], [2 4 6]]
a = np.ndarray(shape=(2,3), dtype=int, buffer=np.array([1, 2, 3, 4, 5, 6, 7]), offset=8, order="C")
print(a)							# output:[[2 3 4], [5 6 7]]

使用empty方法創建

與zeros不同,empty沒有將數組值設置爲0,因此可能會稍微塊一些。另一方面,它要求用戶手動設置數組中的所有值,並且應該謹慎使用;

empty(shape, dtype = float, order = 'C')

參數說明:

參數 描述
shape 多維數組的形狀
dtype 數組中元素的類型,可選
order ‘C’:行優先;‘F’:列優先

實例:

x = np.empty([3,2], dtype=int) 
print(x)
# [[ 6917529027641081856  5764616291768666155]
#  [ 6917529027641081859 -5764598754299804209]
#  [          4497473538      844429428932120]]

使用zeros方法創建

創建指定大小的數組,數組元素以 0 來填充:

zeros(shape, dtype = float, order = 'C')

參數說明:

參數 描述
shape 多維數組的形狀
dtype 數組中元素的類型,可選
order ‘C’:行優先;‘F’:列優先

實例:

# 默認爲浮點數
x = np.zeros(5) 
print(x)							# output:[0. 0. 0. 0. 0.]
 
# 設置類型爲整數
y = np.zeros((5,), dtype = np.int)  
print(y)							# output:[0 0 0 0 0]
 
# 自定義類型
z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])  
print(z)							# output:[[(0, 0) (0, 0)]
									#		   [(0, 0) (0, 0)]]

使用ones方法創建

創建指定形狀的數組,數組元素以 1 來填充:

ones(shape, dtype = None, order = 'C')

參數說明:

參數 描述
shape 多維數組的形狀
dtype 數組中元素的類型,可選
order ‘C’:行優先;‘F’:列優先
# 默認爲浮點數
x = np.ones(5) 
print(x)							# output:[1. 1. 1. 1. 1.] 
# 自定義類型
x = np.ones([2,2], dtype = int)
print(x)							# output:[[1 1]
 											   [1 1]]

使用asarray方法創建

asarray 類似 array,但 asarray 參數只有三個,比 numpy.array 少兩個。

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

參數說明:

參數 描述
a 任意形式的輸入參數,可以是,列表, 列表的元組, 元組, 元組的元組, 元組的列表,多維數組
dtype 數據類型,可選
order 可選,有"C"和"F"兩個選項,分別代表,行優先和列優先,在計算機內存中的存儲元素的順序。

實例:

# 將列表轉換爲 ndarray:
x =  [1,2,3] 
a = np.asarray(x)  
print (a)				# output:[1  2  3]

# 將元組轉換爲 ndarray: 
x =  (1,2,3) 
a = np.asarray(x)  
print (a)				# output:[1  2  3]

# 將元組列表轉換爲 ndarray:
x =  [(1,2,3),(4,5)] 
a = np.asarray(x)  
print (a)
輸出結果爲:
[(1, 2, 3) (4, 5)]

使用frombuffer方法創建

frombuffer 用於實現動態數組。
frombuffer 接受 buffer 輸入參數,以流的形式讀入轉化成 ndarray 對象。

frombuffer(buffer, dtype = float, count = -1, offset = 0)

注意:buffer 是字符串的時候,Python3 默認 str 是 Unicode 類型,所以要轉成 bytestring 在原 str 前加上 b。
參數說明:

參數 描述
buffer 可以是任意對象,會以流的形式讀入。
dtype 返回數組的數據類型,可選
count 讀取的數據數量,默認爲-1,讀取所有數據。
offset 讀取的起始位置,默認爲0。
s =  b'Hello World' 
a = np.frombuffer(s, dtype =  'S1')  
print (a)				# output:[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']

使用fromiter方法調用

fromiter 方法從可迭代對象中建立 ndarray 對象,返回一維數組。

fromiter(iterable, dtype, count=-1)

參數描述:

參數 描述
iterable 可迭代對象
dtype 返回數組的數據類型
count 讀取的數據數量,默認爲-1,讀取所有數據

實例

# 使用 range 函數創建列表對象  
list=range(5)
it=iter(list)
 
# 使用迭代器創建 ndarray 
x=np.fromiter(it, dtype=float)
print(x)					# output:[0. 1. 2. 3. 4.]

使用arange方法創建

numpy 包中的使用 arange 函數創建數值範圍並返回 ndarray 對象,根據 start 與 stop 指定的範圍以及 step 設定的步長,生成一個 ndarray。函數格式如下:

arange(start, stop, step, dtype)

參數說明:

參數 描述
start 起始值,默認爲0
stop 終止值(不包含)
step 步長,默認爲1
dtype 返回ndarray的數據類型,如果沒有提供,則會使用輸入數據的類型。

實例:

# 生成 0 到 5 的數組:
x = np.arange(5)  
print (x)					# output:[0  1  2  3  4]

# 設置返回類型位 float:
# 設置了 dtype
x = np.arange(5, dtype =  float)  
print (x)				    # output:[0.  1.  2.  3.  4.]

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

使用linspace方法創建

linspace 函數用於創建一個一維數組,數組是一個等差數列構成的,格式如下:

linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)

參數說明:

參數 描述
start 序列的起始值
stop 序列的終止值,如果endpoint爲true,該值包含於數列中
num 要生成的等步長的樣本數量,默認爲50
endpoint 該值爲 true 時,數列中中包含stop值,反之不包含,默認是True。
retstep 如果爲 True 時,生成的數組中會顯示間距,反之不顯示。
dtype ndarray 的數據類型

實例

a = np.linspace(1,10,10)
print(a)					# output:[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]

# 設置元素全部是1的等差數列:
a = np.linspace(1,1,10)
print(a)					# output:[1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]

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

# 如果將 endpoint 設爲 true,則會包含 20。
a =np.linspace(1,10,10,retstep= True) 
print(a)
# 拓展例子
b =np.linspace(1,10,10).reshape([10,1])
print(b)
輸出結果爲:
(array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.]), 1.0)
[[ 1.]
 [ 2.]
 [ 3.]
 [ 4.]
 [ 5.]
 [ 6.]
 [ 7.]
 [ 8.]
 [ 9.]
 [10.]]

使用logspace方法創建

logspace 函數用於創建一個於等比數列。格式如下:

logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)

base 參數意思是取對數的時候 log 的下標。

參數 描述
start 序列的起始值爲:base ** start
stop 序列的終止值爲:base ** stop。如果endpoint爲true,該值包含於數列中
num 要生成的等步長的樣本數量,默認爲50
endpoint 該值爲 true 時,數列中中包含stop值,反之不包含,默認是True。
base 對數 log 的底數。
dtype ndarray 的數據類型

實例

# 默認底數是 10
a = np.logspace(1.0,  2.0, num =  10)  
print (a)
# output:
# [ 10.           12.91549665     16.68100537      21.5443469  27.82559402      
#   35.93813664   46.41588834     59.94842503      77.42636827    100.    ]

# 將對數的底數設置爲 2 :
a = np.logspace(0,9,10,base=2)
print (a)				# output:[  1.   2.   4.   8.  16.  32.  64. 128. 256. 512.]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章