Pandas和NumPy函數-筆記轉載

全文共5431字,預計學習時長16分鐘


來源:Pexels


大家都知道Pandas和NumPy函數很棒,它們在日常分析中起着重要的作用。沒有這兩個函數,人們將在這個龐大的數據分析和科學世界中迷失方向。


今天,小芯將分享12個很棒的Pandas和NumPy函數,這些函數將會讓生活更便捷,讓分析事半功倍。


在本文結尾,讀者可以找到文中提到的代碼的JupyterNotebook。


從NumPy開始:


NumPy是使用Python進行科學計算的基本軟件包。它包含以下內容:


· 強大的N維數組對象

· 複雜的(廣播broadcasting)功能

· 集成C / C++和Fortran代碼工具

· 有用的線性代數,傅立葉變換和隨機數功能


除明顯的科學用途外,NumPy是高效的通用數據多維容器,可以定義任意數據類型。這使NumPy能夠無縫且高速地與各種數據庫進行集成。


1. allclose()


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


2. argpartition()


來源:Pexels


NumPy的這個函數非常優秀,可以找到N最大值索引。輸出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])


3. clip()


Clip() 用於將值保留在間隔的數組中。有時,需要將值保持在上限和下限之間。因此,可以使用NumPy的clip()函數。給定一個間隔,該間隔以外的值都將被裁剪到間隔邊緣。


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


4. extract()


顧名思義,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 ifremainder 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])# Applycondition on extract directly
np.extract(((array < 3) | (array > 15)), array)
array([ 0,  1, 19, 16, 18,  2])


5. percentile()


Percentile()用於計算沿指定軸的數組元素的第n個百分位數。


a = np.array([1,5,6,8,1,7,3,6,9])print("50thPercentile 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.13.5 1.9]


6. where()


來源:Pexels


Where() 用於從滿足特定條件的數組中返回元素。它返回在特定條件下值的索引位置。這差不多類似於在SQL中使用的where語句。請看以下示例中的演示。


y = np.array([1,5,6,8,1,7,3,6,9])# Where y is greaterthan 5, returns index position
np.where(y>5)
array([2, 3, 5, 7, 8], dtype=int64),)# First will replace the values that matchthe 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')


接着來講一講神奇的Pandas函數。


Pandas


Pandas是一個Python軟件包,提供快速、靈活和富有表現力的數據結構,旨在使處理結構化(表格,多維,潛在異構)的數據和時間序列數據既簡單又直觀。


Pandas非常適合許多不同類型的數據:


· 具有異構類型列的表格數據,例如在SQL表或Excel電子表格中

· 有序和無序(不一定是固定頻率)的時間序列數據。

· 具有行和列標籤的任意矩陣數據(同類型或異類)

· 觀察/統計數據集的任何其他形式。實際上,數據根本不需要標記,即可放入Pandas數據結構。


以下是Pandas的優勢:


· 輕鬆處理浮點數據和非浮點數據中的缺失數據(表示爲NaN)

· 大小可變性:可以從DataFrame和更高維的對象中插入和刪除列

· 自動和顯式的數據對齊:在計算中,可以將對象顯式對齊到一組標籤,或者用戶可以直接忽略標籤,並讓Series,DataFrame等自動對齊數據

· 強大靈活的分組功能,可對數據集執行拆分-應用-合併操作,以彙總和轉換數據

· 輕鬆將其他Python和NumPy數據結構中的不規則的、索引不同的數據轉換爲DataFrame對象

· 大數據集的智能標籤的切片,高級索引和子集化

· 直觀的合併和聯接數據集

· 數據集的靈活重塑和旋

· 座標軸的分層標籤(每個刻度可能有多個標籤)

· 強大的IO工具,用於從平面文件(CSV和定界文件)、 Excel文件,數據庫加載數據,以及以超高速HDF5格式保存/加載數據

· 特定於時間序列的功能:日期範圍生成和頻率轉換、移動窗口統計、日期移位和滯後。


1. apply()


Apply() 函數允許用戶傳遞函數並將其應用於Pandas序列中每個單一值。


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


2. copy()


Copy()函數用於創建Pandas對象的副本。將數據幀分配給另一個數據幀時,在另一個數據幀中進行更改,其值也會進行同步更改。爲了避免出現上述問題,可以使用copy()函數。


# creating sample series
data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia'])# Assigning issuethat 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)


3. read_csv(nrows=n)


來源:Pexels


讀者可能已經知道了read-csv函數的重要性。但即使不必要,大多數人仍會錯誤地讀取整個.csv文件。假設未知10GB的.csv文件中的列和數據,在這種情況下讀取整個.csv文件並非明智的決定,因爲這會浪費內存和時間。可以僅從.csv中導入幾行,然後根據需要繼續操作。


import io
import requests# I am using this online data set just to make things easier foryou 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)


4. map()


map()函數用於根據輸入對應關係映射Series的值。用於將序列(Series)中的每個值替換爲另一個值,該值可以從函數、字典或序列(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 eachfloating point value in frame
changefn = lambda x: '%.2f' % x# Make changes element-wise
dframe['d'].map(changefn)


5. isin()


Isin() 函數用於過濾數據幀。Isin() 有助於選擇在特定列中具有特定(或多個)值的行。這是筆者見過的最有用的功能。


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


6. select_dtypes()


select_dtypes()函數基於dtypes列返回數據框的列的子集。設置此函數的參數,以包括具有某些特定數據類型的所有列;也可對其進行設置,以排除具有某些特定數據類型的所有列。


# We'll use the same dataframe that we used for read_csv
framex = df.select_dtypes(include="float64")# Returns only time column


福利:


來源:Pexels


Pivot_table()


Pandas最神奇最有用的功能是pivot_table。如果你糾結於是否使用groupby,並想擴展其功能,那麼不妨試試pivot-table。如果明白數據透視表在excel中的工作原理,那麼一切就非常簡單了。數據透視表中的級別將存貯在MultiIndex對象(分層索引)中,而該對象位於DataFrame結果的索引和列上。


# 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


留言 點贊 關注

我們一起分享AI學習與發展的乾貨

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章