import numpy as np_纪录27个NumPy操作
介紹
在上一篇有關21 Pandas操作的文章中,我討論了一些重要的操作,可以幫助新手開始進行數據分析。本文應該為NumPy提供類似的目的。簡要介紹一下,NumPy是一個非常強大的庫,可用于執行各種操作,從查找數組的均值到快速傅立葉變換和信號分析。從這個意義上講,它與MATLAB非常相似。
您將需要將NumPy導入為'np',然后使用它來執行操作。
操作:
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.shape9.了解NumPy數組的尺寸
x = np.array([1,2,3])x.ndim will produce 110.查找NumPy數組中的元素數
x = np.ones((3,2,4),dtype=np.int16)x.size will produce 2411.獲取n維數組占用的內存空間
x.nbytesoutput will be 24*memory occupied by 16 bit integer = 24*2 = 4812.在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 614.獲取n-d數組的轉置
使用array_name.T
x = [[1,2],[3,4]]x1 23 4x.T is1 32 415.展平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 321.比較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 423.兩個陣列的點積
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
總結
以上是生活随笔為你收集整理的import numpy as np_纪录27个NumPy操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python提取文件指定列_如何从csv
- 下一篇: 数字类 default 0和 defau