<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          【Python】50個(gè)常用的 Numpy 函數(shù)詳解

          共 25187字,需瀏覽 51分鐘

           ·

          2023-09-01 08:24

          Numpy是python中最有用的工具之一。它可以有效地處理大容量數(shù)據(jù)。使用NumPy的最大原因之一是它有很多處理數(shù)組的函數(shù)。在本文中,將介紹NumPy在數(shù)據(jù)科學(xué)中最重要和最有用的一些函數(shù)。

          創(chuàng)建數(shù)組

          1、Array

          它用于創(chuàng)建一維或多維數(shù)組

          numpy.array(object, dtype=None, *,
                      copy=True, order='K', subok=False, ndmin=0, like=None)

          Dtype:生成數(shù)組所需的數(shù)據(jù)類型。  
          ndim:指定生成數(shù)組的最小維度數(shù)。

          import numpy as np
          np.array([1,2,3,4,5])
          ----------------
          array([123456])

          還可以使用此函數(shù)將pandas的df和series轉(zhuǎn)為NumPy數(shù)組。

          sex = pd.Series(['Male','Male','Female'])
          np.array(sex)
          ------------------------
          array(['Male''Male''Female'], dtype=object)

          2、Linspace

          創(chuàng)建一個(gè)具有指定間隔的浮點(diǎn)數(shù)的數(shù)組。

          numpy.linspace(start, stop, num=50, endpoint=True,
                         retstep=False, dtype=None, axis=0)[source]

          start:起始數(shù)字
          end:結(jié)束
          Num:要生成的樣本數(shù),默認(rèn)為50。

          np.linspace(10,100,10)
          --------------------------------
          array([ 10.20.30.40.50.60.70.80.90.100.])

          3、Arange

          在給定的間隔內(nèi)返回具有一定步長(zhǎng)的整數(shù)。

          numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None)

          step:數(shù)值步長(zhǎng)。

          np.arange(5,10,2)
          -----------------------
          array([579])

          4、Uniform

          在上下限之間的均勻分布中生成隨機(jī)樣本。

          numpy.random.uniform(low=0.0, high=1.0, size=None)
          np.random.uniform(5,10,size = 4)
          ------------
          array([6.474455715.607258738.821923277.47674099])

          np.random.uniform(size = 5)
          ------------
          array([0.833580920.417761340.72349553])

          np.random.uniform(size = (2,3))
          ------------
          array([[0.7032511 , 0.632120390.6779683 ],
                [0.811508120.268456130.99535264]])

          5、Random.randint

          在一個(gè)范圍內(nèi)生成n個(gè)隨機(jī)整數(shù)樣本。

          numpy.random.randint(low, high=None, size=None, dtype=int)
          np.random.randint(5,10,10)
          ------------------------------
          array([6899769859])

          6、Random.random

          生成n個(gè)隨機(jī)浮點(diǎn)數(shù)樣本。

          numpy.random.random(size=None)
          np.random.random(3)
          ---------------------------
          array([0.876563960.247067160.98950278])

          7、Logspace

          在對(duì)數(shù)尺度上生成間隔均勻的數(shù)字。

          numpy.logspace(start, stop, num=50, endpoint=True,
                         base=10.0, dtype=None, axis=0)

          Start:序列的起始值。
          End:序列的最后一個(gè)值。
          endpoint:如果為True,最后一個(gè)樣本將包含在序列中。
          base:底數(shù)。默認(rèn)是10。

          np.logspace(0,10,5,base=2)
          ------------------
          array([1.00000000e+005.65685425e+00
                 3.20000000e+011.81019336e+02,1.02400000e+03])

          8、zeroes

          np.zeroes會(huì)創(chuàng)建一個(gè)全部為0的數(shù)組。

          numpy.zeros(shape, dtype=float, order='C', *, like=None)

          shape:陣列的形狀。
          Dtype:生成數(shù)組所需的數(shù)據(jù)類型。' int '或默認(rèn)' float '

          np.zeros((2,3),dtype='int')
          ---------------
          array([[000],
                [000]])

          np.zeros(5)
          -----------------
          array([0.0.0.0.0.])

          9、ones

          np.ones函數(shù)創(chuàng)建一個(gè)全部為1的數(shù)組。

          numpy.ones(shape, dtype=None, order='C', *, like=None)
          np.ones((3,4))
          ------------------
          array([[1.1.1.1.],
                [1.1.1.1.],
                [1.1.1.1.]])

          10、full

          創(chuàng)建一個(gè)單獨(dú)值的n維數(shù)組。

          numpy.full(shape, fill_value, dtype=None, order='C', *, like=None)

          fill_value:填充值。

          np.full((2,4),fill_value=2)
          --------------
          array([[2222],
                [2222]])(2,4) : ?????

          11、Identity

          創(chuàng)建具有指定維度的單位矩陣。

          numpy.identity(n, dtype=None, *, like=None)
          np.identity(4)
          ----------
          array([[1.0.0.0.],
                [0.1.0.0.],
                [0.0.1.0.],
                [0.0.0.1.]])#??????? ???? ???? ?? `?????`

          數(shù)組操作

          12、min

          返回?cái)?shù)組中的最小值。

          np.min(a, axis=None, out=None, keepdims=<no value>,
                 initial=<no value>, where=<no value>)

          axis:用于操作的軸。
          out:用于存儲(chǔ)輸出的數(shù)組。

          arr = np.array([1,1,2,3,3,4,5,6,6,2])
          np.min(arr)
          ----------------
          1

          13、max

          返回?cái)?shù)組中的最大值。

          np.max(a, axis=None,out=None)
          np.max(arr)
          ------------------
          6

          14、unique

          返回一個(gè)所有唯一元素排序的數(shù)組。

          numpy.unique(ar, return_index=False, return_inverse=False, return_counts=False, axis=None, *, equal_nan=True)

          return_index:如果為True,返回?cái)?shù)組的索引。
          return_inverse:如果為True,返回唯一數(shù)組的下標(biāo)。
          return_counts:如果為True,返回?cái)?shù)組中每個(gè)唯一元素出現(xiàn)的次數(shù)。
          axis:要操作的軸。默認(rèn)情況下,數(shù)組被認(rèn)為是扁平的。

          np.unique(arr,return_counts=True)
          ---------------------
          (
          array([123456]),             ## Unique elements
          array([222112], dtype=int64) ## Count
          )

          15、mean

          返回?cái)?shù)組的平均數(shù)

          numpy.mean(a, axis=None, dtype=None, out=None)
          np.mean(arr,dtype='int')
          -------------------------------
          3

          16、medain

          返回?cái)?shù)組的中位數(shù)。

          numpy.medain(a, axis=None, out=None)
          arr = np.array([[1,2,3],[5,8,4]])
          np.median(arr)
          -----------------------------
          3.5

          17、digitize

          返回輸入數(shù)組中每個(gè)值所屬的容器的索引。

          numpy.digitize(x, bins, right=False)[source]

          bin:容器的數(shù)組。
          right:表示該間隔是否包括右邊或左邊的bin。

          a = np.array([-0.90.50.911.21.43.64.75.3])
          bins = np.array([0,1,2,3])
          np.digitize(a,bins)
          -------------------------------
          array([011222444], dtype=int64)
          Exp       Value
          x < 0     :   0
          0 <= x <1 :   1
          1 <= x <2 :   2
          2 <= x <3 :   3
          3 <=x     :   4
          Compares -0.9 to 0, here x < 0 so Put 0 in resulting array.
          Compares 0.5 to 0, here 0 <= x <1 so Put 1.
          Compares 5.4 to 4, here 3<=x so Put 4

          18、reshape

          它是NumPy中最常用的函數(shù)之一。它返回一個(gè)數(shù)組,其中包含具有新形狀的相同數(shù)據(jù)。

          numpy.reshape(shap)
          A = np.random.randint(15,size=(4,3))
          A
          ----------------------
          array([[ 8141],
                [ 8114],
                [ 941],
                [131311]])

          A.reshape(3,4)
          -----------------
          array([[ 81418],
                [11494],
                [ 1131311]])

          A.reshape(-1)  
          -------------------
          array([ 81418114941131311])

          19、expand_dims

          它用于擴(kuò)展數(shù)組的維度。

          numpy.expand_dims(a, axis)
          arr = np.array([ 81418114941131311])
          np.expand_dims(A,axis=0)
          -------------------------
          array([[ 81418114941131311]])

          np.expand_dims(A,axis=1)
          ---------------------------
          array([[ 8],
                [14],
                [ 1],
                [ 8],
                [11],
                [ 4],
                [ 9],
                [ 4],
                [ 1],
                [13],
                [13],
                [11]])

          20、squeeze

          通過(guò)移除一個(gè)單一維度來(lái)降低數(shù)組的維度。

          np.squeeze(a, axis=None)
          arr = np.array([[ 8],[14],[ 1],[ 8],[11],[ 4],[ 9],[ 4],[ 1],[13],[13],[11]])
          np.squeeze(arr)
          ---------------------------
          array([ 81418114941131311])

          21、count_nonzero

          計(jì)算所有非零元素并返回它們的計(jì)數(shù)。

          numpy.count_nonzero(a, axis=None, *, keepdims=False)
          a = np.array([0,0,1,1,1,0])
          np.count_nonzero(a)
          --------------------------
          3

          22、argwhere

          查找并返回非零元素的所有下標(biāo)。

          numpy.argwhere(a)
          a = np.array([0,0,1,1,1,0])
          np.argwhere(a)
          ---------------------
          array([[2],[3],[4]], dtype=int64)

          23、argmax & argmin

          argmax返回?cái)?shù)組中Max元素的索引。它可以用于多類圖像分類問(wèn)題中獲得高概率預(yù)測(cè)標(biāo)簽的指標(biāo)。

          numpy.argmax(a, axis=None, out=None, *, keepdims=<no value>)
          arr = np.array([[0.12,0.64,0.19,0.05]])
          np.argmax(arr)
          ---------
          1

          argmin將返回?cái)?shù)組中min元素的索引。

          numpy.argmin(a, axis=None, out=None, *, keepdims=<no value>)
          np.argmin(min)
          ------
          3

          24、sort

          對(duì)數(shù)組排序。

          numpy.sort(a, axis=- 1, kind=None, order=None)

          kind:要使用的排序算法。{‘quicksort’, ‘mergesort’, ‘heapsort’, ‘stable’}

          arr = np.array([2,3,1,7,4,5])
          np.sort(arr)
          ----------------
          array([123457])

          25、abs

          numpy.absolute(x, /, out=None, *, 
                         where=True, casting='same_kind'
                         order='K', dtype=None
                         subok=True[, signature, extobj]) = <ufunc 'absolute'>

          返回?cái)?shù)組中元素的絕對(duì)值。當(dāng)數(shù)組中包含負(fù)數(shù)時(shí),它很有用。

          A = np.array([[1,-3,4],[-2,-4,3]])np.abs(A)
          ---------------
          array([[134],
                [243]])

          26、round

          將浮點(diǎn)值四舍五入到指定數(shù)目的小數(shù)點(diǎn)。

          numpy.around(a, decimals=0, out=None)

          decimals:要保留的小數(shù)點(diǎn)的個(gè)數(shù)。

          a = np.random.random(size=(3,4))
          a
          -----
          array([[0.816956990.425648220.659514170.2731807 ],
                [0.7017702 , 0.125358940.067476660.55733467],
                [0.914644880.262590260.889662370.59253923]])
               

          np.round(a,decimals=0)
          ------------
          array([[1.0.1.1.],
                [1.1.1.1.],
                [0.1.0.1.]])

          np.round(a,decimals=1)
          -------------
          array([[0.80. , 0.60.6],
                [0.50.70.70.8],
                [0.30.90.50.7]])

          27、clip

          numpy.clip(a, a_min, a_max, out=None, **kwargs)

          它可以將數(shù)組的裁剪值保持在一個(gè)范圍內(nèi)。

          arr = np.array([0,1,-3,-4,5,6,7,2,3])
          arr.clip(0,5)
          -----------------
          array([010055523])

          arr.clip(0,3)
          ------------------
          array([010033323])

          arr.clip(3,5)
          ------------------
          array([333355533])

          替換數(shù)組中的值

          28、where

          返回滿足條件的數(shù)組元素。

          numpy.where(condition, [x, y, ]/)

          condition:匹配的條件。如果true則返回x,否則y。

          a = np.arange(12).reshape(4,3)
          a
          -------
          array([[ 012],
                [ 345],
                [ 678],
                [ 91011]])
               
          np.where(a>5)     ## Get The Index
          --------------------
          (array([222333], dtype=int64),
          array([012012], dtype=int64))

          a[np.where(a>5)] ## Get Values
          --------------------------
          array([ 67891011])

          它還可以用來(lái)替換pandas df中的元素。

          np.where(data[feature].isnull(), 10)

          29、put

          用給定的值替換數(shù)組中指定的元素。

          numpy.put(a, ind, v)

          a:數(shù)組
          Ind:需要替換的索引
          V:替換值

          arr = np.array([1,2,3,4,5,6])
          arr
          --------
          array([123456])

          np.put(arr,[1,2],[6,7])
          arr
          --------
          array([167456])

          30、copyto

          將一個(gè)數(shù)組的內(nèi)容復(fù)制到另一個(gè)數(shù)組中。

          numpy.copyto(dst, src, casting='same_kind', where=True)

          dst:目標(biāo)
          src:來(lái)源

          arr1 = np.array([1,2,3])
          arr2 = np.array([4,5,6])
          print("Before arr1",arr1)
          print("Before arr2",arr1)
          np.copyto(arr1,arr2)
          print("After arr1",arr1)
          print("After arr2",arr2)
          ---------------------------
          Before arr1 [1 2 3]
          Before arr2 [4 5 6]

          After arr1 [4 5 6]
          After arr2 [4 5 6]

          集合操作

          31、查找公共元素

          intersect1d函數(shù)以排序的方式返回兩個(gè)數(shù)組中所有唯一的值。

          numpy.intersect1d(ar1, ar2, assume_unique=False, return_indices=False)

          Assume_unique:如果為真值,則假設(shè)輸入數(shù)組都是唯一的。
          Return_indices:如果為真,則返回公共元素的索引。

          ar1 = np.array([1,2,3,4,5,6])
          ar2 = np.array([3,4,5,8,9,1])
          np.intersect1d(ar1,ar2)
          ---------------
          array([1345])

          np.intersect1d(ar1,ar2,return_indices=True)
          ---------------
          (array([1345]),                 ## Common Elements
          array([0234], dtype=int64),    
          array([5012], dtype=int64))

          32、查找不同元素

          numpy.setdiff1d(ar1, ar2, assume_unique=False)

          np.setdiff1d函數(shù)返回arr1中在arr2中不存在的所有唯一元素。

          a = np.array([173241])
          b = np.array([925678])
          np.setdiff1d(a, b)
          ---------------------
          array([134])

          33、從兩個(gè)數(shù)組中提取唯一元素

          numpy.setxor1d(ar1, ar2, assume_unique=False)

          Setxor1d 將按順序返回兩個(gè)數(shù)組中所有唯一的值。

          a = np.array([12346])
          b = np.array([149436])
          np.setxor1d(a,b)
          --------------------
          array([ 236936])

          34、合并

          numpy.union1d(ar1, ar2)

          Union1d函數(shù)將兩個(gè)數(shù)組合并為一個(gè)。

          a = np.array([12345])
          b = np.array([135436])
          np.union1d(a,b)
          -------------------
          array([ 1234536])

          數(shù)組分割

          35、水平分割

          numpy.hsplit(ary, indices_or_sections)

          Hsplit函數(shù)將數(shù)據(jù)水平分割為n個(gè)相等的部分。

          A = np.array([[3,4,5,2],[6,7,2,6]])
          np.hsplit(A,2)   ## splits the data into two equal parts
          ---------------
          [ array([[34],[67]]), array([[52],[26]]) ]

          np.hsplit(A,4)   ## splits the data into four equal parts
          -----------------
          [ array([[3],[6]]), array([[4],[7]]),
            array([[5],[2]]), array([[2],[6]]) ]

          36、垂直分割

          numpy.vsplit(ary, indices_or_sections)

          Vsplit將數(shù)據(jù)垂直分割為n個(gè)相等的部分。

          A = np.array([[3,4,5,2],[6,7,2,6]])
          np.vsplit(A,2)
          ----------------
          [ array([[3452]]), array([[6726]]) ]

          數(shù)組疊加

          37、水平疊加

          numpy.hstack(tup)

          hstack 將在另一個(gè)數(shù)組的末尾追加一個(gè)數(shù)組。

          a = np.array([1,2,3,4,5])
          b = np.array([1,4,9,16,25])

          np.hstack((a,b))
          ---------------------
          array([ 123451491625])

          38、垂直疊加

          numpy.vstack(tup)

          vstack將一個(gè)數(shù)組堆疊在另一個(gè)數(shù)組上。

          np.vstack((a,b))
          ----------------------
          array([[ 12345],
                [ 1491625]])

          數(shù)組比較

          39、allclose

          numpy.allclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)

          如果兩個(gè)數(shù)組的形狀相同,則Allclose函數(shù)根據(jù)公差值查找兩個(gè)數(shù)組是否相等或近似相等。

          a = np.array([0.25,0.4,0.6,0.32])
          b = np.array([0.26,0.3,0.7,0.32])

          tolerance = 0.1           ## Total Difference
          np.allclose(a,b,tolerance)
          ---------
          False

          tolerance = 0.5
          np.allclose(a,b,tolerance)
          ----------
          True

          40、equal

          numpy.equal(x1, x2, /, out=None, *, 
                      where=True, casting='same_kind'
                      order='K', dtype=None, subok=True[, signature, extobj]
                     ) = <ufunc 'equal'>

          它比較兩個(gè)數(shù)組的每個(gè)元素,如果元素匹配就返回True。

          np.equal(arr1,arr2)
          -------------
          array([ TrueTrueTrueFalseTrueTrue])

          重復(fù)的數(shù)組元素

          41、repeat

          它用于重復(fù)數(shù)組中的元素n次。

          numpy.repeat(a, repeats, axis=None)

          A:重復(fù)的元素
          Repeats:重復(fù)的次數(shù)。

          np.repeat('2017',3)
          ---------------------
          array(['2017''2017''2017'], dtype='<U4')

          我們來(lái)看一個(gè)更實(shí)際的示例,我們有一個(gè)包含按年數(shù)量銷售的數(shù)據(jù)集。

          fruits = pd.DataFrame([
            ['Mango',40],
            ['Apple',90],
            ['Banana',130]
          ],columns=['Product','ContainerSales'])
          fruits

          在數(shù)據(jù)集中,缺少年份列。我們嘗試使用numpy添加它。

          fruits['year'] = np.repeat(2020,fruits.shape[0])
          fruits

          42、tile

          通過(guò)重復(fù)A,rep次來(lái)構(gòu)造一個(gè)數(shù)組。

          numpy.title(A, reps)
          np.tile("Ram",5)
          -------
          array(['Ram''Ram''Ram''Ram''Ram'], dtype='<U3')

          np.tile(3,(2,3))
          -------
          array([[333],
                [333]])

          愛(ài)因斯坦求和

          43、einsum

          umpy.einsum(subscripts, *operands, out=None
                      dtype=None, order='K'
                      casting='safe', optimize=False)

          此函數(shù)用于計(jì)算數(shù)組上的多維和線性代數(shù)運(yùn)算。

          a = np.arange(1,10).reshape(3,3)
          b = np.arange(21,30).reshape(3,3)

          np.einsum('ii->i',a)
          ------------
          array([159])

          np.einsum('ji',a)
          ------------
          array([[147],
                [258],
                [369]])
               
          np.einsum('ij,jk',a,b)
          ------------
          array([[150156162],
                [366381396],
                [582606630]])
               
          p.einsum('ii',a)
          ----------
          15

          統(tǒng)計(jì)分析

          44、直方圖

          numpy.histogram(a, bins=10, range=None
                          normed=None, weights=None, density=None)

          這是Numpy的重要統(tǒng)計(jì)分析函數(shù),可計(jì)算一組數(shù)據(jù)的直方圖值。

          A = np.array([[3452],
                      [6726]])
          np.histogram(A)
          -------------------
          (array([2010101021], dtype=int64),
          array([2. , 2.53. , 3.54. , 4.55. , 5.56. , 6.57. ]))

          45、百分位數(shù)

          沿指定軸計(jì)算數(shù)據(jù)的Q-T-T百分位數(shù)。

          numpy.percentile(a, q, axis=None, out=None
                           overwrite_input=False, method='linear'
                           keepdims=False, *, 
                           interpolation=None)[source]

          a:輸入。
          q:要計(jì)算的百分位。
          overwrite_input:如果為true,則允許輸入數(shù)組修改中間計(jì)算以節(jié)省內(nèi)存。

          a = np.array([[246], [4812]])

          np.percentile(a, 50)
          -----------
          5.0

          np.percentile(a, 10)
          ------------
          3.0

          arr = np.array([2,3,4,1,6,7])
          np.percentile(a,5)
          ------------
          2.5

          46、標(biāo)準(zhǔn)偏差

          numpy.std(a, axis=None, dtype=None, out=None
                    ddof=0, keepdims=<no value>, *, 
                    where=<no value>)

          std用于計(jì)算沿軸的標(biāo)準(zhǔn)偏差。

          a = np.array([[246], [4812]])
          np.std(a,axis=1)
          --------
          array([1.632993163.26598632])

          np.std(a,axis=0)   ## Column Wise
          --------
          array([1.2.3.])

          47、方差

          numpy.var(a, axis=None, dtype=None, out=None
                    ddof=0, keepdims=<no value>, *, 
                    where=<no value>)

          var用于計(jì)算沿軸的方差。

          a = np.array([[246], [4812]])
          np.var(a,axis=1)
          -------------------
          array([ 2.6666666710.66666667])

          np.var(a,axis=0)
          -------------------
          array([1.4.9.])

          數(shù)組打印

          48、顯示帶有兩個(gè)十進(jìn)制值的浮點(diǎn)數(shù)

          numpy.set_printoptions(precision=None, threshold=None, edgeitems=None
                                 linewidth=None, suppress=None, nanstr=None, infstr=None
                                 formatter=None, sign=None, floatmode=None, *,
                                 legacy=None)
          np.set_printoptions(precision=2)

          a = np.array([12.2345632.34535])
          print(a)
          ------------
          array([12.23,32.34])

          設(shè)置打印數(shù)組最大值

          np.set_printoptions(threshold=np.inf)

          增加一行中元素的數(shù)量

          np.set_printoptions(linewidth=100## 默認(rèn)是 75

          保存和加載數(shù)據(jù)

          49、保存

          numpy.savetxt(fname, X, fmt='%.18e', delimiter=' '
                        newline='\n', header='', footer=''
                        comments='# ', encoding=None)

          savetxt用于在文本文件中保存數(shù)組的內(nèi)容。

          arr = np.linspace(10,100,500).reshape(25,20)
          np.savetxt('array.txt',arr)

          50、加載

          numpy.loadtxt(fname, dtype=<class 'float'>, comments='#', delimiter=None,
                        converters=Noneskiprows=0, usecols=Noneunpack=False
                        ndmin=0, encoding='bytes', max_rows=None, *, 
                        quotechar=Nonelike=None)

          用于從文本文件加載數(shù)組,它以文件名作為參數(shù)。

          np.loadtxt('array.txt')

          以上就是50個(gè)numpy常用的函數(shù),希望對(duì)你有所幫助。


             
                   
                      
          往期精彩回顧





          瀏覽 292
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  av片电影在线播放 | 午夜中文无码 | 99久高清视频在线观看 | 俺也去在线视频 | 狠狠插狠狠插 |