自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

12個(gè)驚人的Pandas和NumPy函數(shù)

開發(fā) 前端
今天,我將分享12個(gè)驚人的Pandas和NumPy函數(shù),這些函數(shù)將使您的生活和分析變得比以前容易得多。 最后,您可以找到本文所用代碼的Jupyter Notebook。

我們都知道Pandas和NumPy很棒,它們在我們的日常分析中起著至關(guān)重要的作用。沒有Pandas和NumPy,我們將在這個(gè)龐大的數(shù)據(jù)分析和科學(xué)世界中迷茫。今天,我將分享12個(gè)驚人的Pandas和NumPy函數(shù),這些函數(shù)將使您的生活和分析變得比以前容易得多。 最后,您可以找到本文所用代碼的Jupyter Notebook。

12個(gè)驚人的Pandas和NumPy函數(shù)

讓我們從NumPy開始

NumPy是使用Python進(jìn)行科學(xué)計(jì)算的基本軟件包。它包含以下內(nèi)容:

  • 強(qiáng)大的N維數(shù)組對象
  • 復(fù)雜的(廣播)功能
  • 集成C / C++和Fortran代碼的工具
  • 有用的線性代數(shù),傅立葉變換和隨機(jī)數(shù)功能

除了其明顯的科學(xué)用途外,NumPy還可以用作通用數(shù)據(jù)的高效多維容器。可以定義任意數(shù)據(jù)類型。這使NumPy能夠無縫,快速地與各種數(shù)據(jù)庫集成。

1. argpartition()

NumPy具有此驚人的功能,可以找到N個(gè)最大值索引。輸出將是N個(gè)最大值索引,然后可以根據(jù)需要對值進(jìn)行排序。

  1. x = np.array([12, 10, 12, 0, 6, 8, 9, 1, 16, 4, 6, 0]) 
  2. index_val = np.argpartition(x, -4)[-4:] 
  3. index_val 
  4. array([1, 8, 2, 0], dtype=int64
  5. np.sort(x[index_val]) 
  6. array([10, 12, 12, 16]) 

2. allclose()

Allclose()用于匹配兩個(gè)數(shù)組并以布爾值形式獲取輸出。如果兩個(gè)數(shù)組中的項(xiàng)在公差范圍內(nèi)不相等,則將返回False。這是檢查兩個(gè)數(shù)組是否相似的好方法,這實(shí)際上很難手動(dòng)實(shí)現(xiàn)。

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

3. clip()

Clip()用于將值保留在一個(gè)間隔內(nèi)的數(shù)組中。有時(shí),我們需要將值保持在上限和下限之內(nèi)。出于上述目的,我們可以使用NumPy的clip()。給定一個(gè)間隔,該間隔以外的值將被裁剪到間隔邊緣。

  1. x = np.array([3, 17, 14, 23, 2, 2, 6, 8, 1, 2, 16, 0]) 
  2. np.clip(x,2,5) 
  3. array([3, 5, 5, 5, 2, 2, 5, 5, 2, 2, 5, 2]) 

4. extract()

顧名思義,Extract()用于根據(jù)特定條件從數(shù)組中提取特定元素。通過extract(),我們還可以使用諸如and和 or的條件。

  1. # Random integers 
  2. array = np.random.randint(20, size=12
  3. array 
  4. array([ 0,  1,  8, 19, 16, 18, 10, 11,  2, 13, 14,  3]) 
  5. #  Divide by 2 and check if remainder is 1 
  6. cond = np.mod(array, 2)==1 
  7. cond 
  8. array([False,  True, False,  True, False, False, False,  True, False, True, False,  True]) 
  9. # Use extract to get the values 
  10. np.extract(cond, array) 
  11. array([ 1, 19, 11, 13,  3]) 
  12. # Apply condition on extract directly 
  13. np.extract(((array < 3) | (array > 15)), array) 
  14. array([ 0,  1, 19, 16, 18,  2]) 

5. where()

where()用于從滿足特定條件的數(shù)組中返回元素。它返回在特定條件下的值的索引位置。這幾乎類似于我們在SQL中使用的where條件,我將在下面的示例中進(jìn)行演示。

  1. y = np.array([1,5,6,8,1,7,3,6,9]) 
  2. # Where y is greater than 5, returns index position 
  3. np.where(y>5) 
  4. array([2, 3, 5, 7, 8], dtype=int64),) 
  5. # First will replace the values that match the condition,  
  6. # second will replace the values that does not 
  7. np.where(y>5, "Hit", "Miss") 
  8. array(['Miss', 'Miss', 'Hit', 'Hit', 'Miss', 'Hit', 'Miss', 'Hit', 'Hit'],dtype='<U4'

6. percentile()

Percentile()用于計(jì)算沿指定軸的數(shù)組元素的第n個(gè)百分點(diǎn)。

  1. a = np.array([1,5,6,8,1,7,3,6,9]) 
  2. print("50th Percentile of a, axis = 0 : ",   
  3.       np.percentile(a, 50, axis =0)) 
  4. 50th Percentile of a, axis = 0 :  6.0 
  5. b = np.array([[10, 7, 4], [3, 2, 1]]) 
  6. print("30th Percentile of b, axis = 0 : ",   
  7.       np.percentile(b, 30, axis =0)) 
  8. 30th Percentile of b, axis = 0 :  [5.1 3.5 1.9] 

如果您以前使用過它們,請就應(yīng)該能體會(huì)到它對您有多大幫助。讓我們繼續(xù)前進(jìn)到令人驚嘆的Pandas。

pandas:

pandas是一個(gè)Python軟件包,提供快速,靈活和富于表現(xiàn)力的數(shù)據(jù)結(jié)構(gòu),旨在使處理結(jié)構(gòu)化(表格,多維,潛在異構(gòu))和時(shí)間序列數(shù)據(jù)既簡單又直觀。

Pandas非常適合許多不同類型的數(shù)據(jù):

  • 具有異構(gòu)類型列的表格數(shù)據(jù),例如在SQL表或Excel電子表格中
  • 有序和無序(不一定是固定頻率)時(shí)間序列數(shù)據(jù)。
  • 具有行和列標(biāo)簽的任意矩陣數(shù)據(jù)(同類型或異類)
  • 觀察/統(tǒng)計(jì)數(shù)據(jù)集的任何其他形式。實(shí)際上,數(shù)據(jù)根本不需要標(biāo)記即可放入Pandas數(shù)據(jù)結(jié)構(gòu)。

以下是Pandas做得好的一些事情:

  • 輕松處理浮點(diǎn)數(shù)據(jù)和非浮點(diǎn)數(shù)據(jù)中的缺失數(shù)據(jù)(表示為NaN)
  • 大小可變性:可以從DataFrame和更高維的對象中插入和刪除列
  • 自動(dòng)和顯式的數(shù)據(jù)對齊:可以將對象顯式地對齊到一組標(biāo)簽,或者用戶可以簡單地忽略標(biāo)簽并讓Series,DataFrame等自動(dòng)為您對齊數(shù)據(jù)
  • 強(qiáng)大,靈活的分組功能,可對數(shù)據(jù)集執(zhí)行拆分應(yīng)用合并操作,以匯總和轉(zhuǎn)換數(shù)據(jù)
  • 輕松將其他Python和NumPy數(shù)據(jù)結(jié)構(gòu)中的衣衫,、索引不同的數(shù)據(jù)轉(zhuǎn)換為DataFrame對象
  • 基于智能標(biāo)簽的切片,花式索引和大數(shù)據(jù)集子集
  • 直觀的合并和聯(lián)接數(shù)據(jù)集
  • 靈活地重塑和旋轉(zhuǎn)數(shù)據(jù)集
  • 軸的分層標(biāo)簽(每個(gè)刻度可能有多個(gè)標(biāo)簽)
  • 強(qiáng)大的IO工具,用于從平面文件(CSV和定界文件),Excel文件,數(shù)據(jù)庫加載數(shù)據(jù),以及從超快HDF5格式保存/加載數(shù)據(jù)
  • 特定于時(shí)間序列的功能:日期范圍生成和頻率轉(zhuǎn)換,移動(dòng)窗口統(tǒng)計(jì)信息,日期移動(dòng)和滯后。

1. read_csv(nrows = n)

您可能已經(jīng)知道read_csv函數(shù)的使用。但是,即使不需要,我們大多數(shù)人仍然會(huì)錯(cuò)誤地讀取整個(gè).csv文件。讓我們考慮一種情況,即我們不知道10gb的.csv文件中的列和數(shù)據(jù),在這里讀取整個(gè).csv文件將不是一個(gè)明智的決定,因?yàn)檫@將不必要地占用我們的內(nèi)存,并且會(huì)花費(fèi)很多時(shí)間時(shí)間。我們可以僅從.csv文件中導(dǎo)入幾行,然后根據(jù)需要繼續(xù)操作。

  1. import io 
  2. import requests 
  3. # I am using this online data set just to make things easier for you guys 
  4. url = "https://raw.github.com/vincentarelbundock/Rdatasets/master/csv/datasets/AirPassengers.csv" 
  5. s = requests.get(url).content 
  6. # read only first 10 rows 
  7. df = pd.read_csv(io.StringIO(s.decode('utf-8')),nrows=10 , index_col=0

2. map()

map()函數(shù)用于根據(jù)輸入對應(yīng)關(guān)系映射Series的值。用于將系列中的每個(gè)值替換為另一個(gè)值,該值可以從函數(shù),字典或系列中得出。

  1. # create a dataframe 
  2. dframe = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'), index=['India', 'USA', 'China', 'Russia']) 
  3. #compute a formatted string from each floating point value in frame 
  4. changefn = lambda x: '%.2f' % x 
  5. # Make changes element-wise 
  6. dframe['d'].map(changefn) 

3. apply()

apply()允許用戶傳遞一個(gè)函數(shù)并將其應(yīng)用于Pandas系列的每個(gè)單個(gè)值。

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

4. isin()

isin()用于過濾數(shù)據(jù)幀。isin()幫助選擇在特定列中具有特定(或多個(gè))值的行。這是我遇到的最有用的功能。

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

5. copy()

copy()用于創(chuàng)建Pandas對象的副本。將數(shù)據(jù)幀分配給另一個(gè)數(shù)據(jù)幀時(shí),在另一個(gè)數(shù)據(jù)幀中進(jìn)行更改時(shí)其值也會(huì)更改。為了防止出現(xiàn)上述問題,我們可以使用copy()。

  1. # creating sample series  
  2. data = pd.Series(['India', 'Pakistan', 'China', 'Mongolia']) 
  3. # Assigning issue that we face 
  4. datadata1= data 
  5. # Change a value 
  6. data1[0]='USA' 
  7. # Also changes value in old dataframe 
  8. data 
  9. # To prevent that, we use 
  10. # creating copy of series  
  11. new = data.copy() 
  12. # assigning new values  
  13. new[1]='Changed value' 
  14. # printing data  
  15. print(new)  
  16. print(data) 

6. select_dtypes()

select_dtypes()函數(shù)基于列dtypes返回?cái)?shù)據(jù)框的列的子集??梢詫⒋撕瘮?shù)的參數(shù)設(shè)置為包括具有某些特定數(shù)據(jù)類型的所有列,也可以將其設(shè)置為排除具有某些特定數(shù)據(jù)類型的所有那些列。

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

額外的獎(jiǎng)勵(lì):

pivot_table()pandas 最神奇最有用的功能是pivot_table。如果您猶豫使用groupby并想擴(kuò)展其功能,那么可以很好地使用pivot_table。如果您知道數(shù)據(jù)透視表在excel中是如何工作的,那么對您來說可能只是小菜一碟。數(shù)據(jù)透視表中的級別將存儲(chǔ)在結(jié)果DataFrame的索引和列上的MultiIndex對象(分層索引)中。

  1. # Create a sample dataframe 
  2. school = pd.DataFrame({'A': ['Jay', 'Usher', 'Nicky', 'Romero', 'Will'],  
  3.       'B': ['Masters', 'Graduate', 'Graduate', 'Masters', 'Graduate'],  
  4.       'C': [26, 22, 20, 23, 24]}) 
  5. # Lets create a pivot table to segregate students based on age and course 
  6. table = pd.pivot_table(school, values ='A'index =['B', 'C'], columns =['B'], aggfunc = np.sum, fill_value="Not Available")  
  7.    
  8. table 

Jupyter Notebook(使用代碼)可以從以下鏈接找到:

https://github.com/kunaldhariwal/Medium-12-Amazing-Pandas-NumPy-Functions

 

責(zé)任編輯:趙寧寧 來源: 今日頭條
相關(guān)推薦

2020-04-03 13:50:19

數(shù)據(jù)分析PandasNumPy

2024-01-03 14:54:56

PythonPandas數(shù)據(jù)處理工具

2020-05-06 09:18:56

Pandas函數(shù)大數(shù)據(jù)技術(shù)

2021-07-07 09:50:23

NumpyPandasPython

2023-09-08 13:11:00

NumPyPandasPython庫

2023-07-31 11:44:38

Pandas性能數(shù)組

2023-10-15 17:07:35

PandasPython庫

2022-07-06 23:59:57

NumPyPython工具

2022-09-20 10:50:34

PandasNumPy

2021-02-19 10:59:29

NumpyPandasPython

2021-07-13 10:02:52

Pandas函數(shù)Linux

2024-11-12 10:57:14

NumPyPython

2023-08-11 11:19:52

數(shù)據(jù)集Merge函數(shù)

2023-02-08 17:04:14

Python計(jì)算庫數(shù)學(xué)函數(shù)

2020-08-16 10:58:20

Pandaspython開發(fā)

2025-04-03 10:00:00

數(shù)據(jù)分析Pandas數(shù)據(jù)合并

2020-10-29 08:35:06

Pandas函數(shù)Python

2021-05-10 11:40:51

函數(shù)NumpyPython

2020-12-24 07:02:07

CSS框架

2022-07-06 06:17:51

PandasScipynumpy
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號