<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>

          12種Numpy & Pandas高效技巧

          共 9136字,需瀏覽 19分鐘

           ·

          2022-12-30 21:49

          點擊上方小白學(xué)視覺”,選擇加"星標(biāo)"或“置頂

          重磅干貨,第一時間送達


          選自TowardsDataScience,作者:Kunal Dhariwal    機器之心編譯

          本文分享給大家 12 種 Numpy 和 Pandas 函數(shù),這些高效的函數(shù)會令數(shù)據(jù)分析更為容易、便捷。最后,讀者也可以在 GitHub 項目中找到本文所用代碼的 Jupyter Notebook。

          項目地址:https://github.com/kunaldhariwal/12-Amazing-Pandas-NumPy-Functions
          Numpy 的 6 種高效函數(shù)
          首先從 Numpy 開始。Numpy 是用于科學(xué)計算的 Python 語言擴展包,通常包含強大的 N 維數(shù)組對象、復(fù)雜函數(shù)、用于整合 C/C++和 Fortran 代碼的工具以及有用的線性代數(shù)、傅里葉變換和隨機數(shù)生成能力。
          除了上面這些明顯的用途,Numpy 還可以用作通用數(shù)據(jù)的高效多維容器(container),定義任何數(shù)據(jù)類型。這使得 Numpy 能夠?qū)崿F(xiàn)自身與各種數(shù)據(jù)庫的無縫、快速集成。


          接下來一一解析 6 種 Numpy 函數(shù)。
          argpartition()
          借助于 argpartition(),Numpy 可以找出 N 個最大數(shù)值的索引,也會將找到的這些索引輸出。然后我們根據(jù)需要對數(shù)值進行排序。

          x = np.array([1210120689116460])index_val = np.argpartition(x, -4)[-4:]
          index_val
          array([1820], dtype=int64)np.sort(x[index_val])
          array([10121216])

          allclose()
          allclose() 用于匹配兩個數(shù)組,并得到布爾值表示的輸出。如果在一個公差范圍內(nèi)(within a tolerance)兩個數(shù)組不等同,則 allclose() 返回 False。該函數(shù)對于檢查兩個數(shù)組是否相似非常有用。

          array1 = np.array([0.12,0.17,0.24,0.29])
          array2 = np.array([0.13,0.19,0.26,0.31])# with a tolerance of 0.1, it should return False:
          np.allclose(array1,array2,0.1)
          False# with a tolerance of 0.2, it should return True:
          np.allclose(array1,array2,0.2)
          True

          clip()
          Clip() 使得一個數(shù)組中的數(shù)值保持在一個區(qū)間內(nèi)。有時,我們需要保證數(shù)值在上下限范圍內(nèi)。為此,我們可以借助 Numpy 的 clip() 函數(shù)實現(xiàn)該目的。給定一個區(qū)間,則區(qū)間外的數(shù)值被剪切至區(qū)間上下限(interval edge)。

          x = np.array([3171423226812160])np.clip(x,2,5)
          array([355522552252])

          extract()
          顧名思義,extract() 是在特定條件下從一個數(shù)組中提取特定元素。借助于 extract(),我們還可以使用 and 和 or 等條件。
          # Random integers
          array = np.random.randint(20, size=12)
          array
          array([ 0,  1,  81916181011,  21314,  3])#  Divide by 2 and check if remainder is 1
          cond = np.mod(array2)==1
          cond
          array([False,  TrueFalse,  TrueFalseFalseFalse,  TrueFalseTrueFalse,  True])# Use extract to get the values
          np.extract(cond, array)
          array([ 1191113,  3])# Apply condition on extract directly
          np.extract(((array < 3) | (array > 15)), array)
          array([ 0,  1191618,  2])

          where()
          Where() 用于從一個數(shù)組中返回滿足特定條件的元素。比如,它會返回滿足特定條件的數(shù)值的索引位置。Where() 與 SQL 中使用的 where condition 類似,如以下示例所示:
          y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greater than 5, returns index position
          np.where(y>5)
          array([23578], dtype=int64),)# First will replace the values that match the condition, 
          # second will replace the values that does not
          np.where(y>5"Hit""Miss")
          array([ Miss Miss Hit Hit Miss Hit Miss Hit Hit ],dtype= <U4 )

          percentile()
          Percentile() 用于計算特定軸方向上數(shù)組元素的第 n 個百分位數(shù)。
          a = np.array([1,5,6,8,1,7,3,6,9])print("50th Percentile of a, axis = 0 : ",  
                np.percentile(a, 50, axis =0))
          50th Percentile of a, axis = 0 :  6.0b = np.array([[10, 7, 4], [3, 2, 1]])print("30th Percentile of b, axis = 0 : ",  
                np.percentile(b, 30, axis =0))
          30th Percentile of b, axis = 0 :  [5.1 3.5 1.9]

          這就是 Numpy 擴展包的 6 種高效函數(shù),相信會為你帶來幫助。接下來看一看 Pandas 數(shù)據(jù)分析庫的 6 種函數(shù)。

          Pandas 數(shù)據(jù)統(tǒng)計包的 6 種高效函數(shù)
          Pandas 也是一個 Python 包,它提供了快速、靈活以及具有顯著表達能力的數(shù)據(jù)結(jié)構(gòu),旨在使處理結(jié)構(gòu)化 (表格化、多維、異構(gòu)) 和時間序列數(shù)據(jù)變得既簡單又直觀。

          Pandas 適用于以下各類數(shù)據(jù):
          • 具有異構(gòu)類型列的表格數(shù)據(jù),如 SQL 表或 Excel 表;

          • 有序和無序 (不一定是固定頻率) 的時間序列數(shù)據(jù);

          • 帶有行/列標(biāo)簽的任意矩陣數(shù)據(jù)(同構(gòu)類型或者是異構(gòu)類型);

          • 其他任意形式的統(tǒng)計數(shù)據(jù)集。事實上,數(shù)據(jù)根本不需要標(biāo)記就可以放入 Pandas 結(jié)構(gòu)中。

          Pandas 擅長處理的類型如下所示:
          • 容易處理浮點數(shù)據(jù)和非浮點數(shù)據(jù)中的 缺失數(shù)據(jù)(用 NaN 表示);

          • 大小可調(diào)整性: 可以從 DataFrame 或者更高維度的對象中插入或者是刪除列;

          • 顯式數(shù)據(jù)可自動對齊: 對象可以顯式地對齊至一組標(biāo)簽內(nèi),或者用戶可以簡單地選擇忽略標(biāo)簽,使 Series、 DataFrame 等自動對齊數(shù)據(jù);

          • 靈活的分組功能,對數(shù)據(jù)集執(zhí)行拆分-應(yīng)用-合并等操作,對數(shù)據(jù)進行聚合和轉(zhuǎn)換;

          • 簡化將數(shù)據(jù)轉(zhuǎn)換為 DataFrame 對象的過程,而這些數(shù)據(jù)基本是 Python 和 NumPy 數(shù)據(jù)結(jié)構(gòu)中不規(guī)則、不同索引的數(shù)據(jù);

          • 基于標(biāo)簽的智能切片、索引以及面向大型數(shù)據(jù)集的子設(shè)定;

          • 更加直觀地合并以及連接數(shù)據(jù)集;

          • 更加靈活地重塑、轉(zhuǎn)置(pivot)數(shù)據(jù)集;

          • 軸的分級標(biāo)記 (可能包含多個標(biāo)記);

          • 具有魯棒性的 IO 工具,用于從平面文件 (CSV 和 delimited)、 Excel 文件、數(shù)據(jù)庫中加在數(shù)據(jù),以及從 HDF5 格式中保存 / 加載數(shù)據(jù);

          • 時間序列的特定功能: 數(shù)據(jù)范圍的生成以及頻率轉(zhuǎn)換、移動窗口統(tǒng)計、數(shù)據(jù)移動和滯后等。


          read_csv(nrows=n)
          大多數(shù)人都會犯的一個錯誤是,在不需要.csv 文件的情況下仍會完整地讀取它。如果一個未知的.csv 文件有 10GB,那么讀取整個.csv 文件將會非常不明智,不僅要占用大量內(nèi)存,還會花很多時間。我們需要做的只是從.csv 文件中導(dǎo)入幾行,之后根據(jù)需要繼續(xù)導(dǎo)入。
          import io
          import requests# I am using this online data set just to make things easier for you guys
          url = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/datasets/AirPassengers.csv"
          s = requests.get(url).content# read only first 10 rows
          df = pd.read_csv(io.StringIO(s.decode( utf-8 )),nrows=10 , index_col=0)

          map()
          map( ) 函數(shù)根據(jù)相應(yīng)的輸入來映射 Series 的值。用于將一個 Series 中的每個值替換為另一個值,該值可能來自一個函數(shù)、也可能來自于一個 dict 或 Series。
          # create a dataframe
          dframe = pd.DataFrame(np.random.randn(43), columns=list( bde ), index=[ India USA China Russia ])#compute a formatted string from each floating point value in frame
          changefn = lambda x:  %.2f  % x# Make changes element-wise
          dframe[ d ].map(changefn)
          apply()
          apply() 允許用戶傳遞函數(shù),并將其應(yīng)用于 Pandas 序列中的每個值。

          # max minus mix lambda fn
          fn = lambda x: x.max() - x.min()# Apply this on dframe that we ve just created above
          dframe.apply(fn)

          isin()
          lsin () 用于過濾數(shù)據(jù)幀。Isin () 有助于選擇特定列中具有特定(或多個)值的行。

          # Using the dataframe we created for read_csv
          filter1 = df["value"].isin([112]) 
          filter2 = df["time"].isin([1949.000000])df [filter1 & filter2]

          copy()
          Copy () 函數(shù)用于復(fù)制 Pandas 對象。當(dāng)一個數(shù)據(jù)幀分配給另一個數(shù)據(jù)幀時,如果對其中一個數(shù)據(jù)幀進行更改,另一個數(shù)據(jù)幀的值也將發(fā)生更改。為了防止這類問題,可以使用 copy () 函數(shù)。
          # creating sample series 
          data = pd.Series([ India Pakistan China Mongolia ])# Assigning issue that we face
          data1= data
          # Change a value
          data1[0]= USA
          # Also changes value in old dataframe
          data# To prevent that, we use
          # creating copy of series 
          new = data.copy()# assigning new values 
          new[1]= Changed value # printing data 
          print(new
          print(data)

          select_dtypes()
          select_dtypes() 的作用是,基于 dtypes 的列返回數(shù)據(jù)幀列的一個子集。這個函數(shù)的參數(shù)可設(shè)置為包含所有擁有特定數(shù)據(jù)類型的列,亦或者設(shè)置為排除具有特定數(shù)據(jù)類型的列。
          # We ll use the same dataframe that we used for read_csv
          framex =  df.select_dtypes(include="float64")# Returns only time column

          最后,pivot_table( ) 也是 Pandas 中一個非常有用的函數(shù)。如果對 pivot_table( ) 在 excel 中的使用有所了解,那么就非常容易上手了。
          # Create a sample dataframe
          school = pd.DataFrame({ A : [ Jay Usher Nicky Romero Will ], 
                 B : [ Masters Graduate Graduate Masters Graduate ], 
                 C : [2622202324]})# Lets create a pivot table to segregate students based on age and course
          table = pd.pivot_table(school, values = A index =[ B C ], 
                                   columns =[ B ], aggfunc = np.sum, fill_value="Not Available"

          table

          原文鏈接:https://towardsdatascience.com/12-amazing-pandas-numpy-functions-22e5671a45b8

          好消息!

          小白學(xué)視覺知識星球

          開始面向外開放啦??????




          下載1:OpenCV-Contrib擴展模塊中文版教程
          在「小白學(xué)視覺」公眾號后臺回復(fù):擴展模塊中文教程即可下載全網(wǎng)第一份OpenCV擴展模塊教程中文版,涵蓋擴展模塊安裝、SFM算法、立體視覺、目標(biāo)跟蹤、生物視覺、超分辨率處理等二十多章內(nèi)容。

          下載2:Python視覺實戰(zhàn)項目52講
          小白學(xué)視覺公眾號后臺回復(fù):Python視覺實戰(zhàn)項目即可下載包括圖像分割、口罩檢測、車道線檢測、車輛計數(shù)、添加眼線、車牌識別、字符識別、情緒檢測、文本內(nèi)容提取、面部識別等31個視覺實戰(zhàn)項目,助力快速學(xué)校計算機視覺。

          下載3:OpenCV實戰(zhàn)項目20講
          小白學(xué)視覺公眾號后臺回復(fù):OpenCV實戰(zhàn)項目20講即可下載含有20個基于OpenCV實現(xiàn)20個實戰(zhàn)項目,實現(xiàn)OpenCV學(xué)習(xí)進階。

          交流群


          歡迎加入公眾號讀者群一起和同行交流,目前有SLAM、三維視覺、傳感器自動駕駛、計算攝影、檢測、分割、識別、醫(yī)學(xué)影像、GAN算法競賽等微信群(以后會逐漸細分),請掃描下面微信號加群,備注:”昵稱+學(xué)校/公司+研究方向“,例如:”張三 + 上海交大 + 視覺SLAM“。請按照格式備注,否則不予通過。添加成功后會根據(jù)研究方向邀請進入相關(guān)微信群。請勿在群內(nèi)發(fā)送廣告,否則會請出群,謝謝理解~


          瀏覽 42
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <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成人无码精品直播在线 | 国产女人18毛片水18精品软件 | 国产又黄又粗 | 亚洲福利一区二区三区 | 久青久久 |