編寫一個Python程式來修剪資料框中的最小和最大閾值


假設您有一個數據框,以及最小和最大閾值修剪的結果,

minimum threshold:
   Column1 Column2
0    30    30
1    34    30
2    56    30
3    78    50
4    30    90
maximum threshold:
   Column1 Column2
0    12    23
1    34    30
2    50    25
3    50    50
4    28    50
clipped dataframe is:
   Column1 Column2
0    30    30
1    34    30
2    50    30
3    50    50
4    30    50

解決方案

為了解決這個問題,我們將遵循以下步驟:

  • 定義一個數據框

  • 在 (lower=30) 內應用 df.clip 函式來計算最小閾值,

df.clip(lower=30)
  • 在 (upper=50) 內應用 df.clip 函式來計算最大閾值

df.clip(upper=50)
  • 應用帶有最小和最大閾值限制的裁剪資料框,例如:

df.clip(lower=30,upper=50)

示例

讓我們檢查以下程式碼以更好地理解:

import pandas as pd
data = {"Column1":[12,34,56,78,28],
         "Column2":[23,30,25,50,90]}
df = pd.DataFrame(data)
print("DataFrame is:\n",df)
print("minimum threshold:\n",df.clip(lower=30))
print("maximum threshold:\n",df.clip(upper=50))
print("clipped dataframe is:\n",df.clip(lower=30,upper=50))

輸出

DataFrame is:
   Column1 Column2
0    12    23
1    34    30
2    56    25
3    78    50
4    28    90
minimum threshold:
   Column1 Column2
0    30    30
1    34    30
2    56    30
3    78    50
4    30    90
maximum threshold:
   Column1 Column2
0    12    23
1    34    30
2    50    25
3    50    50
4    28    50
clipped dataframe is:
   Column1 Column2
0    30    30
1    34    30
2    50    30
3    50    50
4    30    50

更新於:2021年2月25日

394 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.