在本文中,數據和分析工程師 Kunal Dhariwal 為我們介紹了 12 種 Numpy 和 Pandas 函數,這些高效的函數會令數據分析更為容易、便捷。
首先從 Numpy 開始。Numpy 是用於科學計算的 Python 語言擴展包,通常包含強大的 N 維數組對象、複雜函數、用於整合 C/C++和 Fortran 代碼的工具以及有用的線性代數、傅里葉變換和隨機數生成能力。
除了上面這些明顯的用途,Numpy 還可以用作通用數據的高效多維容器(container),定義任何數據類型。這使得 Numpy 能夠實現自身與各種數據庫的無縫、快速集成。
藉助於 argpartition(),Numpy 可以找出N 個最大數值的索引,也會將找到的這些索引輸出。然後我們根據需要對數值進行排序。
x = np.array([12, 10, 12, 0, 6, 8, 9, 1, 16, 4, 6, 0])index_val = np.argpartition(x, -4)[-4:]index_valarray([1, 8, 2, 0], dtype=int64)np.sort(x[index_val])array([10, 12, 12, 16])
allclose() 用於匹配兩個數組,並得到布爾值表示的輸出。如果在一個公差範圍內(within a tolerance)兩個數組不等同,則 allclose() 返回 False。該函數對於檢查兩個數組是否相似非常有用。
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() 使得一個數組中的數值保持在一個區間內。有時,我們需要保證數值在上下限範圍內。為此,我們可以藉助 Numpy 的 clip() 函數實現該目的。給定一個區間,則區間外的數值被剪切至區間上下限(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(),我們還可以使用 and 和 or 等條件。
# Random integersarray = np.random.randint(20, size=12)arrayarray([ 0, 1, 8, 19, 16, 18, 10, 11, 2, 13, 14, 3])# Divide by 2 and check if remainder is 1cond = np.mod(array, 2)==1condarray([False, True, False, True, False, False, False, True, False, True, False, True])# Use extract to get the valuesnp.extract(cond, array)array([ 1, 19, 11, 13, 3])# Apply condition on extract directlynp.extract(((array < 3) | (array > 15)), array)array([ 0, 1, 19, 16, 18, 2])
Where() 用於從一個數組中返回滿足特定條件的元素。比如,它會返回滿足特定條件的數值的索引位置。Where() 與 SQL 中使用的 where condition 類似,如以下示例所示:
y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greater than 5, returns index positionnp.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 notnp.where(y>5, "Hit", "Miss")array(['Miss', 'Miss', 'Hit', 'Hit', 'Miss', 'Hit', 'Miss', 'Hit', 'Hit'],dtype='<U4')
Percentile() 用於計算特定軸方向上數組元素的第 n 個百分位數。
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 種高效函數,相信會為你帶來幫助。接下來看一看 Pandas 數據分析庫的 6 種函數。
Pandas 也是一個 Python 包,它提供了快速、靈活以及具有顯著表達能力的數據結構,旨在使處理結構化 (表格化、多維、異構) 和時間序列數據變得既簡單又直觀。
具有異構類型列的表格數據,如 SQL 表或 Excel 表
有序和無序 (不一定是固定頻率) 的時間序列數據
帶有行/列標籤的任意矩陣數據(同構類型或者是異構類型)
其他任意形式的統計數據集。事實上,數據根本不需要標記就可以放入 Pandas 結構中
容易處理浮點數據和非浮點數據中的 缺失數據(用 NaN 表示)
大小可調整性:可以從 DataFrame 或者更高維度的對象中插入或者是刪除列
顯式數據可自動對齊:對象可以顯式地對齊至一組標籤內,或者用戶可以簡單地選擇忽略標籤,使 Series、 DataFrame 等自動對齊數據
靈活的分組功能,對數據集執行拆分-應用-合併等操作,對數據進行聚合和轉換
簡化將數據轉換為 DataFrame 對象的過程,而這些數據基本是 Python 和 NumPy 數據結構中不規則、不同索引的數據
基於標籤的智能切片、索引以及面向大型數據集的子設定
更加直觀地合併以及連接數據集
更加靈活地重塑、轉置(pivot)數據集
軸的分級標記 (可能包含多個標記)
具有魯棒性的 IO 工具,用於從平面文件 (CSV 和 delimited)、 Excel 文件、數據庫中加在數據,以及從 HDF5 格式中保存 / 加載數據
時間序列的特定功能:數據範圍的生成以及頻率轉換、移動窗口統計、數據移動和滯後等
大多數人都會犯的一個錯誤是,在不需要.csv 文件的情況下仍會完整地讀取它。如果一個未知的.csv 文件有 10GB,那麼讀取整個.csv 文件將會非常不明智,不僅要占用大量內存,還會花很多時間。我們需要做的只是從.csv 文件中導入幾行,之後根據需要繼續導入。
import ioimport requests# I am using this online data set just to make things easier for you guysurl = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/datasets/AirPassengers.csv"s = requests.get(url).content# read only first 10 rowsdf = pd.read_csv(io.StringIO(s.decode('utf-8')),nrows=10 , index_col=0)
map() 函數根據相應的輸入來映射 Series 的值。用於將一個 Series 中的每個值替換為另一個值,該值可能來自一個函數、也可能來自於一個 dict 或 Series。
# create a dataframedframe = 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 framechangefn = lambda x: '%.2f' % x# Make changes element-wisedframe['d'].map(changefn)
apply() 允許用戶傳遞函數,並將其應用於 Pandas 序列中的每個值。
# max minus mix lambda fnfn = lambda x: x.max() - x.min()# Apply this on dframe that we've just created abovedframe.apply(fn)
lsin () 用於過濾數據幀。Isin () 有助於選擇特定列中具有特定(或多個)值的行。
# Using the dataframe we created for read_csvfilter1 = df["value"].isin([112]) filter2 = df["time"].isin([1949.000000])df [filter1 & filter2]
Copy () 函數用於複製 Pandas 對象。當一個數據幀分配給另一個數據幀時,如果對其中一個數據幀進行更改,另一個數據幀的值也將發生更改。為了防止這類問題,可以使用 copy () 函數。
# creating sample series data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia'])# Assigning issue that we facedata1= data# Change a valuedata1[0]='USA'# Also changes value in old dataframedata# 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() 的作用是,基於 dtypes 的列返回數據幀列的一個子集。這個函數的參數可設置為包含所有擁有特定數據類型的列,亦或者設置為排除具有特定數據類型的列。
# We'll use the same dataframe that we used for read_csvframex = df.select_dtypes(include="float64")# Returns only time column最後,pivot_table() 也是 Pandas 中一個非常有用的函數。如果對 pivot_table() 在 excel 中的使用有所了解,那麼就非常容易上手了。