1. 程式人生 > >numpy中數組的簡單運算以及使用

numpy中數組的簡單運算以及使用

的區別 想要 切片 位數組 註意點 color ugo bsp 加減乘除

import numpy as np

# 定義一個數組
test_array = np.array([[1 ,2 ,3] ,[3 ,4 ,5]])
###數組簡單的加減乘除法
# 加法
print(test_arra y +1)
# 返回[[2 3 4][4 5 6]]

# 減法
print(test_arra y -11)
# 返回[[-10  -9  -8][ -8  -7  -6]]

# 乘法
print(test_arra y *3)
# 返回[[ 3  6  9][ 9 12 15]]

# 除法
print(test_arra y /2)
# 返回[[0.5 1.  1.5][1.5 2.  2.5]]
import numpy as np ###數組的索引和切片 test_arr = np.arange(10) print(test_arr) print(test_arr[1]) print(test_arr[1:5]) """ 運行結果 [0 1 2 3 4 5 6 7 8 9] 1 [1 2 3 4] """ ###使用列表或數組來進行賦值 import numpy as np test_arr = np.arange(10) print(test_arr) test_arr[1:5] = [6,6,6,6] print(test_arr) test_arr[1:5] = np.array([9,9,9,9])
print(test_arr) """ 運行結果 [0 1 2 3 4 5 6 7 8 9] [0 6 6 6 6 5 6 7 8 9] [0 9 9 9 9 5 6 7 8 9] """ ###數組的單元素賦值 import numpy as np test_arr = np.arange(10) print(test_arr) test_arr[1:5] = 12 print(test_arr) """ 運行結果 [0 1 2 3 4 5 6 7 8 9] [ 0 12 12 12 12 5 6 7 8 9] """ # 兩個註意點 # (a)一個標量的賦值瞬間實現整個切片區域的賦值,叫做numpy的廣播功能
# (b)數組切片和列表切片,僅數組切片有廣播功能 ###列表和數組的一個重要的區別 # 跟列表切片最大的區別是數組切片是原數組的視圖,這就意味著原數組數據不會被復制保留,視圖上任何改變都會影響原數組。 # 所以,數組切片賦值會改變原數組,列表切片賦值不會改變願列表,想要改變列表需要直接給列表賦值。 # 二維數組的索引和切片 # 創建一個3x3的二維數組 import numpy as np test_arr = np.arange(9).reshape(3 ,3) print(test_arr) """ 運行結果 [[0 1 2] [3 4 5] [6 7 8]] """ # 取出4 import numpy as np test_arr = np.arange(9).reshape(3 ,3) print(test_arr) print(%test_arr[1 ,1]) # 第一個參數為行號,第二個參數為列號 """ 運行結果 [[0 1 2] [3 4 5] [6 7 8]] 4 """ # 三維數組的索引和切片 # 創建一個有兩個3x3二位數組的三維數組 import numpy as np test_arr = np.arange(18).reshape(2 ,3 ,3 ) # 第一個參數為總共有幾個元素,第二個參數為行號,第三個參數為列號 print(test_arr) """ 運行結果 [[[ 0 1 2] [ 3 4 5] [ 6 7 8]] [[ 9 10 11] [12 13 14] [15 16 17]]] """ # 取出9 print(test_arr[1 ,0 ,0]) # 若array切片時不想改變原array的結構,可以使用copy()先進行拷貝 test_xxx = np.arange(18).reshape(2 ,3 ,3) test_ttt = test_xxx.copy() test_ttt[1 ,0 ,0] = 333 print(test_xxx) print(test_ttt) ###布爾形索引(進行篩選) import numpy as np name = np.array([wiz ,gougou ,ac ,lc]) score = np.array([[99 ,99 ,99] ,[88 ,88 ,88] ,[81 ,87 ,66] ,[100 ,100 ,100]]) print(score[name==gougou]) """ 運行結果 [[88 88 88]] """ ###數組的轉置 arr = np.arange(16).reshape(2 ,2 ,4) print(arr) print(arr.T) ###numpy的基本數學統計方法 # 方差(體現數組中數據的離散情況,數值越小數據越穩定) arr = np.arange(16).reshape(2 ,4 ,2) print(arr.var()) # 標準差 print(arr.std())

numpy中數組的簡單運算以及使用