[學習筆記]虛樹
阿新 • • 發佈:2020-11-22
將列表轉換成 ndarray:
import numpy as np ls1 = [10, 42, 0, -17, 30] nd1 =np.array(ls1) print(nd1) print(type(nd1))
執行結果: [ 10 42 0 -17 30] <class 'numpy.ndarray'>
巢狀列表可以轉換成多維 ndarray: import numpy as np ls2 = [[8, -2, 0, 34, 7], [6, 7, 8, 9, 10]] nd2 =np.array(ls2) print(nd2) print(type(nd2))
執行結果: [[ 8 -2 0 34 7] [ 6 7 8 9 10]] <class 'numpy.ndarray'>
#利用 random 模組生成陣列 import numpy as np import random nd3 =np.random.random([4, 3]) #生成4行3列的陣列 print(nd3) print("nd3的形狀為:",nd3.shape)
#執行結果: [[0.59115057 0.52022516 0.05992361] [0.5077815 0.81313999 0.70061259] [0.24654561 0.11705634 0.71399966] [0.73964407 0.57138345 0.89284498]] nd3的形狀為: (4, 3)
#使用 shuffle() 函式打亂生成的隨機數。 import numpy as np np.random.seed(123) nd4 = np.random.randn(4, 3) print(nd4) np.random.shuffle(nd4) print("隨機打亂後資料:") print(nd4) print(type(nd4))
執行結果: 複製程式碼 [[-1.0856306 0.99734545 0.2829785 ] [-1.50629471 -0.57860025 1.65143654] [-2.42667924 -0.42891263 1.26593626] [-0.8667404 -0.67888615 -0.09470897]] 隨機打亂後資料: [[-1.50629471 -0.57860025 1.65143654] [-2.42667924 -0.42891263 1.26593626] [-0.8667404 -0.67888615 -0.09470897] [-1.0856306 0.99734545 0.2829785 ]] <class 'numpy.ndarray'>