1、番外說明
大家好,我是小P,本系列是本人對Python模塊Numpy的一些學習記錄,總結於此一方面方便其它初學者學習,另一方面害怕自己遺忘,希望大家喜歡。此外,對“目標檢測/模型壓縮/語義分割”感興趣的小夥伴,歡迎加入QQ羣 813221712 討論交流,進羣請看羣公告!(可以點擊如下連接直接加入!)
點擊鏈接加入羣聊【Object Detection】:https://jq.qq.com/?_wv=1027&k=5kXCXF8
2、正題
參考鏈接:
http://www.runoob.com/numpy/numpy-array-from-existing-data.html
2.1 numpy.asarray函數
numpy.asarray 類似 numpy.array,但 numpy.asarray 只有三個,比 numpy.array 少兩個。
numpy.asarray(a, dtype = None, order = None)
參數說明:
實例:將列表轉換爲 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.]
2.2 numpy.frombuffer
numpy.frombuffer 用於實現動態數組。
numpy.frombuffer 接受 buffer 輸入參數,以流的形式讀入轉化成 ndarray 對象。
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)
注意:buffer 是字符串的時候,Python3 默認 str 是 Unicode 類型,所以要轉成 bytestring 在原 str 前加上 b。
參數說明:
實例: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']
2.3 numpy.fromiter
numpy.fromiter 方法從可迭代對象中建立 ndarray 對象,返回一維數組。
numpy.fromiter(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.]