top
Loading...
NumPy 從已有的數組創建數組

NumPy 從已有的數組創建數組

本章節我們將學習如何從已有的數組創建數組。

numpy.asarray

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

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

參數說明:

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

實例

將列表轉換為 ndarray:

實例

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

輸出結果為:

[1  2  3]

將元組轉換為 ndarray:

實例

import numpy as np x = (1,2,3) a = np.asarray(x) print (a)

輸出結果為:

[1  2  3]

將元組列表轉換為 ndarray:

實例

import numpy as np x = [(1,2,3),(4,5)] a = np.asarray(x) print (a)

輸出結果為:

[(1, 2, 3) (4, 5)]

設置了 dtype 參數:

實例

import numpy as np x = [1,2,3] a = np.asarray(x, dtype = float) print (a)

輸出結果為:

[ 1.  2.  3.]

numpy.frombuffer

numpy.frombuffer 用於實現動態數組。

numpy.frombuffer 接受 buffer 輸入參數,以流的形式讀入轉化成 ndarray 對象。

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

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

參數說明:

參數 描述
buffer 可以是任意對象,會以流的形式讀入。
dtype 返回數組的數據類型,可選
count 讀取的數據數量,默認為-1,讀取所有數據。
offset 讀取的起始位置,默認為0。

Python3.x 實例

import numpy as np s = b'Hello World' a = np.frombuffer(s, dtype = 'S1') print (a)

輸出結果為:

[b'H' b'e' b'l' b'l' b'o' b' ' b'W' b'o' b'r' b'l' b'd']

Python2.x 實例

import numpy as np s = 'Hello World' a = np.frombuffer(s, dtype = 'S1') print (a)

輸出結果為:

['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']

numpy.fromiter

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

numpy.fromiter(iterable, dtype, count=-1)
參數 描述
iterable 可疊代對象
dtype 返回數組的數據類型
count 讀取的數據數量,默認為-1,讀取所有數據

實例

import numpy as np # 使用 range 函數創建列表對象 list=range(5) it=iter(list) # 使用疊代器創建 ndarray x=np.fromiter(it, dtype=float) print(x)

輸出結果為:

[0. 1. 2. 3. 4.]
北斗有巢氏 有巢氏北斗