Python 數(shù)據(jù)處理更容易的12個(gè)輔助函數(shù)總結(jié)
大家好,今天給大家分享 12 個(gè) Python 函數(shù),其中 Numpy 和 Pandas 各6個(gè),這些實(shí)用的函數(shù)會(huì)令數(shù)據(jù)處理更為容易、便捷。
同時(shí),你也可以在 GitHub 項(xiàng)目中找到本文所用代碼的 Jupyter Notebook,歡迎收藏學(xué)習(xí),喜歡點(diǎn)贊支持。
項(xiàng)目地址:https://github.com/kunaldhariwal/12-Amazing-Pandas-NumPy-Functions
Numpy 的 6 種高效函數(shù)
首先從 Numpy 開(kāi)始。Numpy 是用于科學(xué)計(jì)算的 Python 語(yǔ)言擴(kuò)展包,通常包含強(qiáng)大的 N 維數(shù)組對(duì)象、復(fù)雜函數(shù)、用于整合 C/C++和 Fortran 代碼的工具以及有用的線性代數(shù)、傅里葉變換和隨機(jī)數(shù)生成能力。
除了上面這些明顯的用途,Numpy 還可以用作通用數(shù)據(jù)的高效多維容器(container),定義任何數(shù)據(jù)類(lèi)型。這使得 Numpy 能夠?qū)崿F(xiàn)自身與各種數(shù)據(jù)庫(kù)的無(wú)縫、快速集成。
接下來(lái)一一解析 6 種 Numpy 函數(shù)。
argpartition()
借助于 argpartition(),Numpy 可以找出 N 個(gè)最大數(shù)值的索引,也會(huì)將找到的這些索引輸出。然后我們根據(jù)需要對(duì)數(shù)值進(jìn)行排序。
x = np.array([12, 10, 12, 0, 6, 8, 9, 1, 16, 4, 6, 0])index_val = np.argpartition(x, -4)[-4:] index_val array([1, 8, 2, 0], dtype=int64)np.sort(x[index_val]) array([10, 12, 12, 16])
allclose()
allclose() 用于匹配兩個(gè)數(shù)組,并得到布爾值表示的輸出。如果在一個(gè)公差范圍內(nèi)(within a tolerance)兩個(gè)數(shù)組不等同,則 allclose() 返回 False。該函數(shù)對(duì)于檢查兩個(gè)數(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() 使得一個(gè)數(shù)組中的數(shù)值保持在一個(gè)區(qū)間內(nèi)。有時(shí),我們需要保證數(shù)值在上下限范圍內(nèi)。為此,我們可以借助 Numpy 的 clip() 函數(shù)實(shí)現(xiàn)該目的。給定一個(gè)區(qū)間,則區(qū)間外的數(shù)值被剪切至區(qū)間上下限(interval edge)。
x = np.array([3, 17, 14, 23, 2, 2, 6, 8, 1, 2, 16, 0])np.clip(x,2,5) array([3, 5, 5, 5, 2, 2, 5, 5, 2, 2, 5, 2])
extract()
顧名思義,extract() 是在特定條件下從一個(gè)數(shù)組中提取特定元素。借助于 extract(),我們還可以使用 and 和 or 等條件。
# Random integers array = np.random.randint(20, size=12) array array([ 0, 1, 8, 19, 16, 18, 10, 11, 2, 13, 14, 3])# Divide by 2 and check if remainder is 1 cond = np.mod(array, 2)==1 cond array([False, True, False, True, False, False, False, True, False, True, False, True])# Use extract to get the values np.extract(cond, array) array([ 1, 19, 11, 13, 3])# Apply condition on extract directly np.extract(((array < 3) | (array > 15)), array) array([ 0, 1, 19, 16, 18, 2])
where()
Where() 用于從一個(gè)數(shù)組中返回滿足特定條件的元素。比如,它會(huì)返回滿足特定條件的數(shù)值的索引位置。Where() 與 SQL 中使用的 where condition 類(lèi)似,如以下示例所示:
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([2, 3, 5, 7, 8], 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() 用于計(jì)算特定軸方向上數(shù)組元素的第 n 個(gè)百分位數(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.0 b = 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 擴(kuò)展包的 6 種高效函數(shù),相信會(huì)為你帶來(lái)幫助。接下來(lái)看一看 Pandas 數(shù)據(jù)分析庫(kù)的 6 種函數(shù)。
Pandas 數(shù)據(jù)統(tǒng)計(jì)包的 6 種高效函數(shù)
Pandas 也是一個(gè) Python 包,它提供了快速、靈活以及具有顯著表達(dá)能力的數(shù)據(jù)結(jié)構(gòu),旨在使處理結(jié)構(gòu)化 (表格化、多維、異構(gòu)) 和時(shí)間序列數(shù)據(jù)變得既簡(jiǎn)單又直觀。
Pandas 適用于以下各類(lèi)數(shù)據(jù):
- 具有異構(gòu)類(lèi)型列的表格數(shù)據(jù),如 SQL 表或 Excel 表;
- 有序和無(wú)序 (不一定是固定頻率) 的時(shí)間序列數(shù)據(jù);
- 帶有行/列標(biāo)簽的任意矩陣數(shù)據(jù)(同構(gòu)類(lèi)型或者是異構(gòu)類(lèi)型);
- 其他任意形式的統(tǒng)計(jì)數(shù)據(jù)集。事實(shí)上,數(shù)據(jù)根本不需要標(biāo)記就可以放入 Pandas 結(jié)構(gòu)中。
Pandas 擅長(zhǎng)處理的類(lèi)型如下所示:
- 容易處理浮點(diǎn)數(shù)據(jù)和非浮點(diǎn)數(shù)據(jù)中的 缺失數(shù)據(jù)(用 NaN 表示);
- 大小可調(diào)整性: 可以從 DataFrame 或者更高維度的對(duì)象中插入或者是刪除列;
- 顯式數(shù)據(jù)可自動(dòng)對(duì)齊: 對(duì)象可以顯式地對(duì)齊至一組標(biāo)簽內(nèi),或者用戶可以簡(jiǎn)單地選擇忽略標(biāo)簽,使 Series、 DataFrame 等自動(dòng)對(duì)齊數(shù)據(jù);
- 靈活的分組功能,對(duì)數(shù)據(jù)集執(zhí)行拆分-應(yīng)用-合并等操作,對(duì)數(shù)據(jù)進(jìn)行聚合和轉(zhuǎn)換;
- 簡(jiǎn)化將數(shù)據(jù)轉(zhuǎn)換為 DataFrame 對(duì)象的過(guò)程,而這些數(shù)據(jù)基本是 Python 和 NumPy 數(shù)據(jù)結(jié)構(gòu)中不規(guī)則、不同索引的數(shù)據(jù);
- 基于標(biāo)簽的智能切片、索引以及面向大型數(shù)據(jù)集的子設(shè)定;
- 更加直觀地合并以及連接數(shù)據(jù)集;
- 更加靈活地重塑、轉(zhuǎn)置(pivot)數(shù)據(jù)集;
- 軸的分級(jí)標(biāo)記 (可能包含多個(gè)標(biāo)記);
- 具有魯棒性的 IO 工具,用于從平面文件 (CSV 和 delimited)、 Excel 文件、數(shù)據(jù)庫(kù)中加在數(shù)據(jù),以及從 HDF5 格式中保存 / 加載數(shù)據(jù);
- 時(shí)間序列的特定功能: 數(shù)據(jù)范圍的生成以及頻率轉(zhuǎn)換、移動(dòng)窗口統(tǒng)計(jì)、數(shù)據(jù)移動(dòng)和滯后等。
read_csv(nrows=n)
大多數(shù)人都會(huì)犯的一個(gè)錯(cuò)誤是,在不需要.csv 文件的情況下仍會(huì)完整地讀取它。如果一個(gè)未知的.csv 文件有 10GB,那么讀取整個(gè).csv 文件將會(huì)非常不明智,不僅要占用大量?jī)?nèi)存,還會(huì)花很多時(shí)間。我們需要做的只是從.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)的輸入來(lái)映射 Series 的值。用于將一個(gè) Series 中的每個(gè)值替換為另一個(gè)值,該值可能來(lái)自一個(gè)函數(shù)、也可能來(lái)自于一個(gè) dict 或 Series。
# create a dataframe dframe = pd.DataFrame(np.random.randn(4, 3), 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 序列中的每個(gè)值。
# 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 () 用于過(guò)濾數(shù)據(jù)幀。Isin () 有助于選擇特定列中具有特定(或多個(gè))值的行。
# 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 對(duì)象。當(dāng)一個(gè)數(shù)據(jù)幀分配給另一個(gè)數(shù)據(jù)幀時(shí),如果對(duì)其中一個(gè)數(shù)據(jù)幀進(jìn)行更改,另一個(gè)數(shù)據(jù)幀的值也將發(fā)生更改。為了防止這類(lèi)問(wèn)題,可以使用 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 的列返回?cái)?shù)據(jù)幀列的一個(gè)子集。這個(gè)函數(shù)的參數(shù)可設(shè)置為包含所有擁有特定數(shù)據(jù)類(lèi)型的列,亦或者設(shè)置為排除具有特定數(shù)據(jù)類(lèi)型的列。
# 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 中一個(gè)非常有用的函數(shù)。如果對(duì) pivot_table( ) 在 excel 中的使用有所了解,那么就非常容易上手了。
# Create a sample dataframe school = pd.DataFrame({ A : [ Jay , Usher , Nicky , Romero , Will ], B : [ Masters , Graduate , Graduate , Masters , Graduate ], C : [26, 22, 20, 23, 24]})# 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
技術(shù)交流
歡迎轉(zhuǎn)載、收藏、有所收獲點(diǎn)贊支持一下!
到此這篇關(guān)于輔助Python 數(shù)據(jù)處理更容易的12個(gè)函數(shù)總結(jié)的文章就介紹到這了,更多相關(guān)Python 數(shù)據(jù)處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python基本數(shù)據(jù)類(lèi)型及內(nèi)置方法
這篇文章主要介紹了Python基本數(shù)據(jù)類(lèi)型及內(nèi)置方法,??數(shù)據(jù)類(lèi)型是用來(lái)記錄事物狀態(tài)的,而事物的狀態(tài)是不斷變化的,下文圍繞主題展開(kāi)相關(guān)內(nèi)容需要的小伙伴可以參考一下2022-04-04python之文件的讀寫(xiě)和文件目錄以及文件夾的操作實(shí)現(xiàn)代碼
這篇文章主要介紹了python之文件的讀寫(xiě)和文件目錄以及文件夾的操作實(shí)現(xiàn)代碼,需要的朋友可以參考下2016-08-08Python selenium 加載并保存QQ群成員,去除其群主、管理員信息的示例代碼
這篇文章主要介紹了Python selenium 加載并保存QQ群成員 去除其群主、管理員信息的示例代碼,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2020-05-05Python?torch.onnx.export用法詳細(xì)介紹
這篇文章主要給大家介紹了關(guān)于Python?torch.onnx.export用法詳細(xì)介紹的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-07-07對(duì)tensorflow中tf.nn.conv1d和layers.conv1d的區(qū)別詳解
今天小編就為大家分享一篇對(duì)tensorflow中tf.nn.conv1d和layers.conv1d的區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02Python Pandas批量讀取csv文件到dataframe的方法
這篇文章主要介紹了Python Pandas批量讀取csv文件到dataframe的方法,需要的朋友可以參考下2018-10-10編程小妙招:Python帶你玩轉(zhuǎn)Excel超鏈接
掌握Python實(shí)現(xiàn)Excel加超鏈接的技巧,讓你的數(shù)據(jù)報(bào)告活起來(lái),本指南將帶你輕松穿梭于單元格間,一行代碼搞定鏈接,別等了,跟我一起讓你的Excel工作表不僅聰明,還能“點(diǎn)”亮你的信息網(wǎng)絡(luò)!2023-12-12Python dict和defaultdict使用實(shí)例解析
這篇文章主要介紹了Python dict和defaultdict使用實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03Python數(shù)據(jù)預(yù)處理常用的5個(gè)技巧
大家好,本篇文章主要講的是Python數(shù)據(jù)預(yù)處理常用的5個(gè)技巧,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下2022-02-02