Pandas 的 qcut(~)
方法將數值分類為分位數箱(間隔),以便每個箱中的項目數量相等。
參數
1. x
| array-like
一個一維輸入數組,其數值將被分段到容器中。
2. q
| int
或 sequence<number>
或 IntervalIndex
分位數的數量。如果 q=4
,則將計算四分位數。您還可以傳入四分位數數組(例如 [0, 0.1, 0.5, 1]
]。
3. labels
| array
或 False
| optional
所需的箱子標簽。默認情況下,labels=None
。
4. retbins
| boolean
| optional
是否返回箱子。默認情況下,retbins=False
。
5. precision
| int
| optional
容器標簽中包含的小數位數。默認情況下,precision=3
。
6. duplicates
| string
| optional
如何處理重複的 bin 邊:
值 |
說明 |
---|---|
|
如果設置了任何重複的 bin 邊,則會拋出錯誤。 |
|
刪除重複的箱子邊並隻保留一個。 |
默認情況下,duplicates="raise"
。
返回值
如果 retbins=False
,則返回類型取決於 labels
參數的值:
-
如果未指定
labels
,則返回對每個值的 bin 進行編碼的Series
或Categorical
。 -
如果提供數組,則返回
Series
或Categorical
。 -
如果提供布爾值
False
,則返回 NumPy 整數數組。
如果 retbins=True
,則除了上述內容之外,容器還將作為 NumPy 數組返回。如果 x
是 IntervalIndex
,則返回 x
。
例子
考慮以下有關學生及其成績的DataFrame:
raw_grades = [3,6,8,7,3,5]
students = ["alex", "bob", "cathy", "doge", "eric", "fred"]
df = pd.DataFrame({"name":students,"raw_grade":raw_grades})
df
name raw_grade
0 alex 3
1 bob 6
2 cathy 8
3 doge 7
4 eric 3
5 fred 5
基本用法
將原始等級分為四個箱(段):
df["grade"] = pd.qcut(df["raw_grade"], q=4)
df
name raw_grade grade
0 alex 3 (2.999, 3.5]
1 bob 6 (5.5, 6.75]
2 cathy 8 (6.75, 8.0]
3 doge 7 (6.75, 8.0]
4 eric 3 (2.999, 3.5]
5 fred 5 (3.5, 5.5]
這裏的四個四分位數如下:
1st: (2.999, 3.5]
2nd: (3.5, 5.5]
3rd: (5.5, 6.75]
4th: (6.75, 8.0]
請注意, (2.995, 3.5]
僅表示 2.999 < raw_grade <= 3.5
。
指定四分位數
要指定自定義四分位數,我們可以傳入四分位數 array
而不是 int
:
df["grade"] = pd.qcut(df["raw_grade"], q=[0, .4, .8, 1])
df
name raw_grade grade
0 alex 3 (2.999, 5.0]
1 bob 6 (5.0, 7.0]
2 cathy 8 (7.0, 8.0]
3 doge 7 (5.0, 7.0]
4 eric 3 (2.999, 5.0]
5 fred 5 (2.999, 5.0]
指定標簽
我們可以通過設置labels
參數來為我們的箱子添加標簽:
df["grade"] = pd.qcut(df["raw_grade"], q=4, labels=["D","C","B","A"])
df
name raw_grade grade
0 alex 3 D
1 bob 6 B
2 cathy 8 A
3 doge 7 A
4 eric 3 D
5 fred 5 C
這是qcut(~)
方法的一個非常實用的函數。這裏,labels
數組的長度必須等於指定的四分位數。
指定 retbins
要獲得計算的 bin 邊,請設置 retbins=True
:
x = [3,6,8,7,4,5]
res = pd.cut(x, bins=2, retbins=True)
print("Categories: ", res[0])
print("Bin egdes: ", res[1])
Categories: [(2.999, 4.5], (4.5, 6.0], (6.75, 8.0], (6.75, 8.0], (2.999, 4.5], (4.5, 6.0]]
Categories (4, interval[float64]): [(2.999, 4.5] < (4.5, 6.0] < (6.0, 6.75] < (6.75, 8.0]]
Bin egdes: [ 3. 4.5 6. 6.75 8. ]
指定精度
為了控製顯示多少位小數,請設置precision
參數:
x = [3,6,8,7,4,5]
bins = pd.qcut(x, q=4, precision=2)
print(bins)
[(2.99, 4.25], (5.5, 6.75], (6.75, 8.0], (6.75, 8.0], (2.99, 4.25], (4.25, 5.5]]
Categories (4, interval[float64]): [(2.99, 4.25] < (4.25, 5.5] < (5.5, 6.75] < (6.75, 8.0]]
在這裏,2.999
被截斷為 2.99
,因為我們將 precision
設置為 2
。
指定重複項
默認情況下,bin 邊必須是唯一的,否則將引發錯誤。例如:
x = [3,6,8,7,3,5]
pd.qcut(x, q=5) # duplicates="raise"
ValueError: Bin edges must be unique: array([ 3., 3., 5., 6., 7., 8.]).
在這裏,我們最終得到了值為 3 的兩個 bin 邊,因此這就是我們收到錯誤的原因。
為了刪除(刪除)多餘的 bin 邊,請設置 duplicates="drop"
,如下所示:
x = [3,6,8,7,3,5]
pd.qcut(x, q=5, duplicates="drop")
[(2.999, 5.0], (5.0, 6.0], (7.0, 8.0], (6.0, 7.0], (2.999, 5.0], (2.999, 5.0]]
Categories (4, interval[float64]): [(2.999, 5.0] < (5.0, 6.0] < (6.0, 7.0] < (7.0, 8.0]]
相關用法
- Python queue.PriorityQueue用法及代碼示例
- Python NumPy quantile方法用法及代碼示例
- Python cudf.core.column.string.StringMethods.is_vowel用法及代碼示例
- Python NumPy fliplr方法用法及代碼示例
- Python torch.distributed.rpc.rpc_async用法及代碼示例
- Python torch.nn.InstanceNorm3d用法及代碼示例
- Python sklearn.cluster.MiniBatchKMeans用法及代碼示例
- Python pandas.arrays.IntervalArray.is_empty用法及代碼示例
- Python tf.compat.v1.distributions.Multinomial.stddev用法及代碼示例
- Python numpy.less()用法及代碼示例
- Python Matplotlib.figure.Figure.add_gridspec()用法及代碼示例
- Python tf.compat.v1.distribute.MirroredStrategy.experimental_distribute_dataset用法及代碼示例
- Python Django File.save用法及代碼示例
- Python NumPy squeeze方法用法及代碼示例
- Python Sympy Permutation.list()用法及代碼示例
- Python dask.dataframe.Series.apply用法及代碼示例
- Python networkx.algorithms.shortest_paths.weighted.all_pairs_dijkstra_path用法及代碼示例
- Python scipy.ndimage.binary_opening用法及代碼示例
- Python NumPy char find方法用法及代碼示例
- Python pyspark.pandas.Series.dropna用法及代碼示例
- Python torchaudio.transforms.Fade用法及代碼示例
- Python dask.dataframe.to_records用法及代碼示例
- Python arcgis.gis._impl._profile.ProfileManager.save_as用法及代碼示例
- Python pyspark.pandas.groupby.SeriesGroupBy.unique用法及代碼示例
- Python distributed.protocol.serialize.register_generic用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas | qcut method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。