Pandas DataFrame中列的百分位秩
查詢百分位秩是一種常見的操作,用於比較單個數據集中的資料。此操作的最終結果顯示某個百分比大於或等於指定的百分位數。例如,假設一名學生的分數大於或等於所有其他分數的80%。那麼,該學生的百分位秩就是第80位。
要查詢Pandas DataFrame中列的百分位秩,我們可以使用Python提供的名為“rank()”和“percentile()”的內建方法。
Python程式:查詢Pandas中列的百分位秩
在繼續之前,讓我們熟悉一下Pandas DataFrame。它是一個開源的Python庫,主要用於資料分析和處理。它可以透過對指定資料執行各種操作(例如清理、過濾、分組、聚合和合並)來處理關係資料和標籤資料。
現在,是時候深入研究示例程式了。
示例1
在下面的示例中,我們將使用內建方法“percentile()”來計算百分位秩。
方法
第一步是匯入pandas和numpy包。
建立一個名為“df”的DataFrame,其中包含兩列“Name”和“Score”。
接下來,使用“percentile()”方法計算百分位秩。我們將直接將此方法應用於“Score”列,並將列本身作為資料陣列和所需的百分位數傳遞。它還帶有一個可選引數“method”,用於指定當所需的百分位數落在兩個資料點之間時要使用的插值方法。在本例中,它設定為“nearest”,這意味著將返回最近的秩。
最後,將生成的百分位數分配給一個名為“Per_Rank”的新列,並使用“print()”方法顯示結果。
# importing packages
import pandas as pd
import numpy as np
# defining a sample DataFrame using pandas
data = {'Name': ['Ram', 'Shyam', 'Shrey', 'Mohan', 'Navya'],
'Score': [75, 82, 68, 90, 88] }
df = pd.DataFrame(data)
# Calculating the percentile rank using numpy
df['Per_Rank'] = np.percentile(df['Score'], df['Score'], method = 'nearest')
# to show the result
print(df)
輸出
Name Score Per_Rank 0 Ram 75 88 1 Shyam 82 88 2 Shrey 68 88 3 Mohan 90 90 4 Navya 88 90
示例2
以下示例說明了使用“rank()”方法查詢百分位秩。
方法
首先,使用引用名稱“pd”匯入pandas包。
建立一個包含兩列“Name”和“Score”的Pandas DataFrame。
接下來,建立一個使用者定義的方法“percentile_rank()”,並帶有一個名為“column”的引數。在此方法內部,透過將“pct”引數設定為True來使用內建方法“rank()”,以便它可以返回該列的百分位秩。
現在,透過將df['Score']作為引數傳遞,將“percentile_rank()”方法應用於“Score”列,然後將結果儲存到一個名為“Per_Rank”的新列中。
最後,使用“print()”方法顯示結果並退出。
# importing the required package
import pandas as pd
# defining a sample DataFrame using pandas
data = {'Name': ['Ram', 'Shyam', 'Shrey', 'Mohan', 'Navya'],
'Score': [55, 92, 68, 70, 88] }
df = pd.DataFrame(data)
# user-defined method Calculating the percentile rank
def percentile_rank(column):
return column.rank(pct = True)
# calling the user-defined method
df['Per_Rank'] = percentile_rank(df['Score'])
# to show the result
print(df)
輸出
Name Score Per_Rank 0 Ram 55 0.2 1 Shyam 92 1.0 2 Shrey 68 0.4 3 Mohan 70 0.6 4 Navya 88 0.8
示例3
在這個例子中,我們將修改前面示例中的程式碼,定義一個名為“Balance”的新列,並將rank()方法應用於它,而不是“Score”列。
# importing the required package
import pandas as pd
# defining a sample DataFrame using pandas
data = {'Name': ['Ram', 'Shyam', 'Shrey', 'Mohan', 'Navya'],
'Balance': [5500, 9200, 6800, 7000, 8800]}
df = pd.DataFrame(data)
# user-defined method Calculating the percentile rank
def percentile_rank(column):
return column.rank(pct = True)
# calling the user-defined method
df['Per_Rank'] = percentile_rank(df['Balance'])
# to show the result
print(df)
輸出
Name Balance Per_Rank 0 Ram 5500 0.2 1 Shyam 9200 1.0 2 Shrey 6800 0.4 3 Mohan 7000 0.6 4 Navya 8800 0.8
結論
在本文中,我們討論了幾種計算百分位秩的方法,包括“rank()”和“percentile()”。我們透過指定pct = True使用了“rank()”方法,並透過傳遞列名作為引數使用了percentile()方法。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP