Pandas DataFrame.clip(~) 方法用於確保 DataFrame 的值在特定範圍內。
參數
1.lower | scalar 或 array_like | optional
要剪輯的下限。小於 lower 的值將被 lower 替換。您可以通過傳入 None 來忽略下限。
2. upper | scalar 或 array_like | optional
要剪輯的上限。大於 upper 的值將被 upper 替換。您可以通過傳入 None 來忽略上限。
3. axis | int 或 string | optional
是否對每行或每列進行裁剪:
|
軸 |
說明 |
|---|---|
|
|
剪輯整個 DataFrame 。 |
|
|
對每列按元素進行剪輯。 |
|
|
對每行按元素進行剪輯。 |
默認情況下,axis=None 。當您傳入 lower 或 upper 的數組時,應根據需要將 axis 設置為 0 或 1。請參閱下麵的示例以進行說明。
4. inplace | boolean | optional
是否直接修改源DataFrame而不創建新的。默認情況下, inplace=False ,即,將返回一個新的 DataFrame ,並且源 DataFrame 將保持不變。
返回值
其值被剪裁的 DataFrame。
例子
基本用法
考慮以下 DataFrame :
df = pd.DataFrame({"A":[2,4],"B":[6,8]})
df
A B
0 2 6
1 4 8
下限和上限分別設置為 3 和 6 的裁剪:
df.clip(lower=3, upper=6)
A B
0 3 6
1 4 6
在此,請注意以下事項:
-
DataFrame 中小於
3的任何值都將被值3替換。 -
任何大於
6的值都將被值6替換。 -
最後, DataFrame 中的最小值應為
3,最大值應為6。
傳入一個數組
剪裁每一列
考慮與上麵相同的DataFrame:
df
A B
0 2 6
1 4 8
我們可以傳入一個邊界數組,如下所示:
df.clip(lower=[5,2], axis=0)
A B
0 5 6
1 4 8
在這裏,從 axis=0 開始,我們逐個元素地剪切每一列。分解正在發生的事情:
Column A: [5 2] lower clips [2 4] = [5 4]
Column B: [5 2] lower clips [6 8] = [6 8]
我們還可以設置數組和數字的組合,如下所示:
df.clip(lower=[5,2], upper=6, axis=0)
A B
0 5 6
1 4 6
分解正在發生的事情:
Column A: [5 2] lower clips [2 4] = [5 4] -> upper clipped to [5 4]
Column B: [5 2] lower clips [6 8] = [6 8] -> upper clipped to [6 6]
剪裁每一行
這裏再次df供您參考:
df
A B
0 2 6
1 4 8
設置 axis=1 按元素剪輯每行:
df.clip(lower=[5,2], upper=6, axis=1)
A B
0 5 6
1 5 6
再次,這是細分:
Column One: [5 2] lower clips [2 6] = [5 6] -> upper clipped to [5 6]
Column Two: [5 2] lower clips [4 8] = [5 8] -> upper clipped to [5 6]
相關用法
- Python Pandas DataFrame copy方法用法及代碼示例
- Python PySpark DataFrame collect方法用法及代碼示例
- Python PySpark DataFrame coalesce方法用法及代碼示例
- Python Pandas DataFrame cummax方法用法及代碼示例
- Python Pandas DataFrame corrwith方法用法及代碼示例
- Python PySpark DataFrame corr方法用法及代碼示例
- Python Pandas DataFrame cumprod方法用法及代碼示例
- Python Pandas DataFrame convert_dtypes方法用法及代碼示例
- Python Pandas DataFrame combine方法用法及代碼示例
- Python Pandas DataFrame cummin方法用法及代碼示例
- Python Pandas DataFrame columns屬性用法及代碼示例
- Python PySpark DataFrame cov方法用法及代碼示例
- Python Pandas DataFrame count方法用法及代碼示例
- Python PySpark DataFrame colRegex方法用法及代碼示例
- Python PySpark DataFrame columns屬性用法及代碼示例
- Python Pandas DataFrame cumsum方法用法及代碼示例
- Python PySpark DataFrame count方法用法及代碼示例
- Python Pandas DataFrame corr方法用法及代碼示例
- Python Pandas DataFrame combine_first方法用法及代碼示例
- Python Pandas DataFrame cov方法用法及代碼示例
- Python Pandas DataFrame empty屬性用法及代碼示例
- Python Pandas DataFrame pop方法用法及代碼示例
- Python Pandas DataFrame nsmallest方法用法及代碼示例
- Python Pandas DataFrame sample方法用法及代碼示例
- Python Pandas DataFrame items方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas DataFrame | clip method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
