Numpy提供了一個在Python中作科學計算的基礎庫,重在數值計算,主要用於處理多維數組(矩陣)的庫。用來存儲和處理大型矩陣,比Python自身的嵌套列表結構要高效的多。自己是由C語言開發,是個很基礎的擴展,Python其他的科學計算擴展大部分都是以此爲基礎。python
高性能科學計算和數據分析的基礎包數組
ndarray,多維數組(矩陣),具備矢量運算能力,快速、節省空間dom
矩陣運算,無需循環,可完成相似Matlab中的矢量運算ide
線性代數、隨機數生成函數
import random import numpy as np # numpy是幫助咱們進行數值型計算的 a = np.array([1,2,3,4,5]) print(a) # [1 2 3 4 5] print(type(a)) # <class 'numpy.ndarray'> b = np.array(range(1,6)) print(b) print(type(b)) c = np.arange(1,6) print(c) print(type(c)) # dtype:查看數組中數據的類型 print(c.dtype) # int64,默認是根據電腦位數來的 # 指定生成的數據類型 d = np.array([1,1,0,1],dtype=bool) print(d) # [ True True False True] # numpy中的小數 e = np.array([random.random() for i in range(4)]) print(e) # [0.8908038 0.4591454 0.38334215 0.08534364] print(type(e)) # <class 'numpy.ndarray'> print(e.dtype) # float64 # 取數據的幾位小數 f = e.round(2) # 或者 f = np.round(e,2) print(f) # [0.92 0.27 0.07 0.94]
import numpy as np # 數組的形狀 a = np.array([[1,3,4],[3,5,6]]) print(a) """ 二維數組 [[1 3 4] [3 5 6]] """ print(a.shape) # (2,3),表明着2行3列的數組 b = np.array([[[1,2,3],[4,5,6]],[[1,2,3],[4,5,6]]]) print(b) """ 三維數組 [[[1 2 3] [4 5 6]] [[1 2 3] [4 5 6]]] """ print(b.shape) # (2, 2, 3) # 因爲上面這種寫法(幾維數組)過於複雜 c = np.arange(12) # 生成一個一維數組 d = np.reshape(c,(3,4)) # 將1維數組轉變成3*4的二維數組 print(d) """ 3*4的二維數組 [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] """ e = np.arange(24) f = e.reshape((2,3,4)) print(f) """ 2*3*4的三維數組,其中2表示塊數,3行4列 [[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]] """ # 三種方式將3維數組f,轉成1維數組 g = f.reshape((24,)) # 必定要有, f.reshape((1,24))也行 h = f.reshape((f.shape[0]*f.shape[1]*f.shape[2],)) i = f.flatten() print(g) print(h) print(i)
import numpy as np # 數組的計算 a = np.array([i for i in range(12)]) b = a.reshape((3,4)) # 2維數組 print(b) """ [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] """ print(b+2) """ numpy會將數組中的全部元素+2,+—*/同理,下面看一個特殊的 [[ 2 3 4 5] [ 6 7 8 9] [10 11 12 13]] """ # print(b/0) """ 在numpy中,/0並不會報錯,其中nan(not a number)表明未定義或不可表示的值,inf(infimum)表示無窮 [[nan inf inf inf] [inf inf inf inf] [inf inf inf inf]] """ # 兩個相同結構的數組的+——*/ c = np.array([1,2,3,4]) d = np.array([5,6,7,8]) e = c.reshape((2,2)) f = d.reshape((2,2)) print(e+f) """ e: [[1 2] [3 4]] f: [[5 6 [7 8]] e+f: [[ 6 8] [10 12]] """ # 由於行的維度兩個數組是相同的,因此會對每一行進行+——*/運算 # 多維中有一個(或以上)維度相同的話就能夠進行計算 # 全部維度都不相同,沒法進行計算
""" 加載csv數據 """ us_file_path = "./youtube_video_data/US_video_data_numbers.csv" uk_file_path = "./youtube_video_data/GB_video_data_numbers.csv" """ fname:文件路徑 delimiter:數據分隔符(默認爲空格) dtype:數據類型 skiprows:跳過多少行 usecols:選取指定的列(元組類型) unpack:是否轉置 """ aaa = np.loadtxt(fname=us_file_path,delimiter=",",dtype=int)
a = np.array([i for i in range(12)]) b = a.reshape((3,4)) print(b) """ 轉置的3中方法 轉置:2維數組的行和列交換 """ print(b.T) print(b.transpose()) # 交換0軸和1軸 print(b.swapaxes(1,0))
""" 取行/列 """ # 取第3行 print(b[2]) # 取連續的多行(2~4行) print(b[1:4]) # 取不連續的多行(一、3行) print(b[[0,2]]) # 取第2列 print(b[:,1]) # 取連續的多列(1~3列) print(b[:,0:3]) # 取不連續的多列(1,3列) print(b[:,[0,2]]) # 取行列交叉的點(3行4列) c = b[2,3] print(c) print(type(c)) #取多行和多列,取第3行到第五行,第2列到第4列的結果 #去的是行和列交叉點的位置 print(b[2:5,1:4]) #取多個不相鄰的點 #選出來的結果是(0,0) (2,1) (2,3) print(b[[0,2,2],[0,1,3]])
""" numpy中的布爾索引 """ print(b) """ [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] """ print(b>5) """ [[False False False False] [False False True True] [ True True True True]] """ # Demo:將數組中>5的值改爲5 print(b[b>5]) # [ 6 7 8 9 10 11] b[b>5] = 5 """ numpy中的三元運算 """ # b中小於4的==>0,大於等於4的==>10 c = np.where(b<4,0,10) # 注意:不會修改b,而是有一個返回值 print(c) """ numpy中的裁剪 """ # 小於10的替換成10,大於18的替換成18 b.clip(10,18)
nan(NAN,Nan):not a number表示不是一個數字性能
何時numpy中會出現nan:spa
inf(-inf,inf):infinity,inf表示正無窮,-inf表示負無窮3d
何時回出現inf包括(-inf,+inf)對象
inf和nan都是float類型blog
那麼問題來了,在一組數據中單純的把nan替換爲0,合適麼?會帶來什麼樣的影響?
好比,所有替換爲0後,替換以前的平均值若是大於0,替換以後的均值確定會變小,因此更通常的方式是把缺失的數值替換爲均值(中值)或者是直接刪除有缺失值的一行
那麼問題來了:
求和:t.sum(axis=None)
均值:t.mean(a,axis=None) 受離羣點的影響較大
中值:np.median(t,axis=None)
最大值:t.max(axis=None)
最小值:t.min(axis=None)
極值:np.ptp(t,axis=None) 即最大值和最小值只差
標準差:t.std(axis=None)
默認返回多維數組的所有的統計結果,若是指定axis則返回一個當前軸上的結果
Demo:將數組中的nan替換成平均值
import numpy as np def fill_ndarray(t1): # 對每列進行操做 for i in range(t1.shape[1]): # 獲取當前列 temp_col = t1[:,i] # 判斷這列中有沒有nan nan_number = np.count_nonzero(temp_col!=temp_col) if nan_number > 0: # 獲取當前列中不爲nan的數組 temp_not_nan_col = temp_col[temp_col==temp_col] # 找出nan,替換成平均值,或temp_col(np.isnan(temp_col)) = temp_not_nan_col.mean() temp_col[temp_col!=temp_col] = temp_not_nan_col.mean() return t1 if __name__ == '__main__': t1 = np.arange(24).reshape((4, 6)).astype("float") # 將第二行的3列之後賦值爲nan t1[1, 2:] = np.nan t2 = fill_ndarray(t1) print(t2)
獲取最大值最小值的位置
np.argmax(t,axis=0)
np.argmin(t,axis=1)
建立一個全0的數組: np.zeros((3,4))
建立一個全1的數組: np.ones((3,4))
建立一個對角線爲1的正方形數組(方陣):np.eye(3)
a=b 徹底不復制,a和b相互影響
a = b[:],視圖的操做,一種切片,會建立新的對象a,可是a的數據徹底由b保管,他們兩個的數據變化是一致的,
a = b.copy(),複製,a和b互不影響
二維數組的軸:
三維數組的軸: