import numpy as np什麼意思_紀錄27個NumPy操作
介紹
在上一篇有關21 Pandas操作的文章中,我討論了一些重要的操作,可以幫助新手開始進行資料分析。本文應該為NumPy提供類似的目的。簡要介紹一下,NumPy是一個非常強大的庫,可用於執行各種操作,從查詢陣列的均值到快速傅立葉變換和訊號分析。從這個意義上講,它與MATLAB非常相似。
您將需要將NumPy匯入為'np',然後使用它來執行操作。
操作:
- 將列表轉換為n維NumPy陣列
numpy_array = np.array(list_to_convert)
2.使用np.newaxis和np.reshape
np.newaxis用於建立大小為1的新尺寸。
a = [1,2,3,4,5] is a lista_numpy = np.array(a)
如果列印a_numpy.shape,您會得到(5,)。為了使它成為行向量或列向量,可以
row_vector = a_numpy[:,np.newaxis] ####shape is (5,1) nowcol_vector = a_numpy[np.newaxis,:] ####shape is (1,5) now
類似地,np.reshape可以用來對任何陣列進行整形。例如:
a = range(0,15) ####list of numbers from 0 to 14b = a.reshape(3,5) b would become:[[0,1,2,3,4], [5,6,7,8,9], [10,11,12,13,14], [15,16,17,18,19]]
3.將任何資料型別轉換為NumPy陣列
使用np.asarray。例如
a = [(1,2), [3,4,(5)], (6,7,8)]b = np.asarray(a)b::array([(1, 2), list([3, 4, (5, 6)]), (6, 7, 8)], dtype=object)
4.獲得零的n維陣列。
a = np.zeros(shape,dtype=type_of_zeros)type of zeros can be int or float as it is requiredeg.a = np.zeros((3,4), dtype = np.float16)
5.獲得一個n維陣列。
類似於np.zeros:
a = np.ones((3,4), dtype=np.int32)
6. np.full和np.empty
np.full用於獲取由一個特定值填充的陣列,而np.empty通過使用隨機值初始化陣列來幫助建立陣列。例如。
1. np.full(shape_as_tuple,value_to_fill,dtype=type_you_want)a = np.full((2,3),1,dtype=np.float16)a would be:array([[1., 1., 1.], [1., 1., 1.]], dtype=float16)2. np.empty(shape_as_tuple,dtype=int)a = np.empty((2,2),dtype=np.int16)a would be:array([[25824, 25701], [ 2606, 8224]], dtype=int16) The integers here are random.
7.使用np.arrange和np.linspace獲取均勻間隔的值的陣列
兩者都可以用來建立具有均勻間隔的元素的陣列。
linspace:
np.linspace(start,stop,num=50,endpoint=bool_value,retstep=bool_value)endpoint specifies if you want the stop value to be included and retstep tells if you would like to know the step-value.'num' is the number of integer to be returned where 50 is default Eg,np.linspace(1,2,num=5,endpoint=False,retstep=True)This means return 5 values starting at 1 and ending befor 2 and returning the step-size.output would be:(array([1. , 1.2, 1.4, 1.6, 1.8]), 0.2) ##### Tuple of numpy array and step-size
人氣指數:
np.arange(start=where_to_start,stop=where_to_stop,step=step_size)
如果僅提供一個數字作為引數,則將其視為停止,如果提供2,則將其視為開始和停止。注意這裡的拼寫。
8.找到NumPy陣列的形狀
array.shape
9.瞭解NumPy陣列的尺寸
x = np.array([1,2,3])x.ndim will produce 1
10.查詢NumPy陣列中的元素數
x = np.ones((3,2,4),dtype=np.int16)x.size will produce 24
11.獲取n維陣列佔用的記憶體空間
x.nbytesoutput will be 24*memory occupied by 16 bit integer = 24*2 = 48
12.在NumPy陣列中查詢元素的資料型別
x = np.ones((2,3), dtype=np.int16)x.dtype will producedtype('int16')It works better when elements in the array are of one type otherwise typecasting happens and result may be difficult to interpret.
13.如何建立NumPy陣列的副本
使用np.copy
y = np.array([[1,3],[5,6]])x = np.copy(y)If,x[0][0] = 1000Then,x is100 35 6y is1 35 6
14.獲取n-d陣列的轉置
使用array_name.T
x = [[1,2],[3,4]]x1 23 4x.T is1 32 4
15.展平n-d陣列以獲得一維陣列
使用np.reshape和np.ravel:
np.reshape:這確實是一個不錯的選擇。在重塑時,如果您提供-1作為尺寸之一,則從no推斷出來。的元素。例如。對於尺寸陣列,(1,3,4)如果將其調整為,(-1,2,2),則第一維的長度計算為3。所以,
If x is:1 2 34 5 9Then x.reshape(-1) produces:array([1, 2, 3, 4, 5, 9])
np.ravel
x = np.array([[1, 2, 3], [4, 5, 6]])x.ravel() producesarray([1, 2, 3, 4, 5, 6])
16.更改n-d陣列的軸或交換尺寸
使用np.moveaxis和np.swapaxes。
x = np.ones((3,4,5))np.moveaxis(x,axes_to_move_as_list, destination_axes_as_list)For eg.x.moveaxis([1,2],[0,-2])This means you want to move 1st axis to 0th axes and 2nd axes to 2nd last axis. So,the new shape would be.(4,5,3)
轉換沒有到位,所以不要忘記將其儲存在另一個變數中。
np.swapaxes。
x = np.array([[1,2],[3,4]])x.shape is (2,2) and x is1 23 4np.swapaxes(x,0,1) will produce1 32 4If x = np.ones((3,4,5)), andy = np.swapaxes(0,2)y.shape will be(5,4,3)
17.將NumPy陣列轉換為列表
x = np.array([[3,4,5,9],[2,6,8,0]])y = x.tolist()y will be[[3, 4, 5, 9], [2, 6, 8, 0]]
NumPy文件提到,list(x)如果x是一維陣列,使用也將起作用。
18.更改NumPy陣列中元素的資料型別。
使用ndarray.astype
x = np.array([0,1,2.0,3.0,4.2],dtype=np.float32)x.astype(np.int16) will producearray([0, 1, 2, 3, 4], dtype=int16)x.astype(np.bool) will produce array([False, True, True, True, True])
19.獲取非零元素的索引
使用n-dim_array.nonzero()
x = np.array([0,1,2.0,3.0,4.2],dtype=np.float32)x.nonzero() will produce(array([1, 2, 3, 4]),) It's important to note that x has shape (5,) so only 1st indices are returned. If x were say,x = np.array([[0,1],[3,5]])x.nonzero() would produce (array([0, 1, 1]), array([1, 0, 1]))So, the indices are actually (0,1), (1,0), (1,1).
20.對NumPy陣列進行排序
使用np.ndarray.sort(axis = axis_you_want_to_sort_by)
x = np.array([[4,3],[3,2])x is4 33 2x.sort(axis=1) #sort each row3 42 3x.sort(axis=0) #sort each col3 24 3
21.比較NumPy陣列和值
比較將產生布爾型別的NumPy n維陣列。例如
x = np.array([[0,1],[2,3]])x==1 will producearray([[False, True], [False, False]])
如果您想計算x中的數字,您可以這樣做
(x==1).astype(np.int16).sum()
它應該輸出 1
22.乘以兩個NumPy矩陣
使用numpy.matmul來獲取二維矩陣的矩陣乘積:
a = np.eye(2) #identity matrix of size 2a1 00 1b = np.array([[1,2],[3,4]])b1 23 4np.matmul(a,b) will give1 23 4
如果我們提供一維陣列,則輸出將非常不同,因為將使用廣播。我們在下面討論。此外,還有另一個函式稱為np.multiply執行元素到元素的乘法。對於前兩個矩陣,輸出為np.multiply(a,b)。
1 00 4
23.兩個陣列的點積
np.dot(矩陣1,矩陣2)
a = np.array([[1,2,3],[4,8,16]])a:1 2 34 8 16b = np.array([5,6,11]).reshape(-1,1)b:5611np.dot(a,b) produces38160Just like any dot product of a matrix with a column vector would produce.
行向量與列向量的點積將產生:
if a is array([[1, 2, 3, 4]])and b is: array([[4], [5], [6], [7]])np.dot(a,b) gives:array([[60]])a's shape was (1,4) and b's shape was (4,1) so the result will have shape (1,1)
24.獲得兩個numpy向量的叉積
回想一下物理學中的向量叉積。這是大約一個點的扭矩方向。
x = [1,2,3]y = [4,5,6]z = np.cross(x, y)z is:array([-3, 6, -3])
25.獲取陣列的梯度
使用np.gradient。NumPy使用泰勒級數和中心差法計算梯度。您可以在這篇文章中閱讀有關它的更多資訊。
x = np.array([5, 10, 14, 17, 19, 26], dtype=np.float16)np.gradient(x) will be:array([5. , 4.5, 3.5, 2.5, 4.5, 7. ], dtype=float16)
26.如何切片NumPy陣列?
For single element:x[r][c] where r,c are row and col number of the element.For slicing more than one element.x:2 4 93 1 57 8 0and you want 2,4 and 7,8 then dox[list_of_rows,list_of_cols] which would bex[[0,0,2,2],[0,1,0,1]] producesarray([2, 4, 7, 8])If one of the rows or cols are continuous, it's easier to do it:x[[0,2],0:2] producesarray([[2, 4], [7, 8]])
27. broadcasting
如果不包括broadcasting,則有關NumPy的任何文章都將是不完整的。這是一個重要的概念,可幫助NumPy對操作進行向量化,從而使計算速度更快。理解一些規則將有助於更好地剖析廣播。
來自NumPy文件:
在兩個陣列上進行操作時,NumPy逐元素比較其形狀。它從尾隨尺寸開始,一直向前發展。兩種尺寸相容
1.他們是平等的,或
2.其中之一是1
要記住的另一件事是,
如果尺寸匹配,則輸出將在每個尺寸中具有最大長度。如果其中一個維度的長度為1,則將重複該維度中的值
假設有兩個陣列A和維度說明B **(3,4,5)**和**(4,1) **分別,你想新增的兩個陣列。由於它們的形狀不同,因此NumPy將嘗試廣播這些值。它開始比較兩個尺寸的最後一個維度的長度:5和1,這些值不相等,但是由於其中一個值為1,因此將重複該值,最終輸出在最後一個維度中的長度為5 。
兩者的倒數第二個長度相同4。
A中的最後3維或1維具有長度,3而B沒有任何長度。當其中一個向量缺少維度時,NumPy在向量前加1。因此,B變為**(1,4,1)**。現在,長度匹配為3和1,並且在B中將值重複3次。最終輸出將具有shape **(3,4,5)**。
a :3 5 84 5 69 7 2b :b = [2,3,4]a's shape: (3,3)b's shape: (3,)Last dimension has same length 3 for the two and then 1 is prepended to the the dimension of b as it doesn't have anything in that dimension. So, b becomes [[2,3,4]] having shape (1,3). Now, 1st dimension match and values are repeated for b. Finally, b can be seen as2 3 42 3 42 3 4So, a+b produces5 8 126 8 1011 10 6
檢視broadcasting中的這些帖子以瞭解更多資訊:第一和第二
總結
感謝您的閱讀。我希望本文能為需要NumPy入門的任何人提供幫助。我發現這些操作非常有幫助,將它們放在我們的提示上總是一件好事。這些操作非常基礎,NumPy中可能有不同的方法來實現相同的目標。除了提供了連結的其他幾篇文章外,我主要使用NumPy文件作為參考。
翻譯自:https://towardsdatascience.com/27-things-that-a-beginner-needs-to-know-about-numpy-edda217fb662