怎么用python刪除異常值

小億
215
2023-11-29 12:54:07
欄目: 編程語言

使用Python刪除異常值的一種常見方法是使用統(tǒng)計(jì)學(xué)中的標(biāo)準(zhǔn)差方法。具體步驟如下:

  1. 導(dǎo)入必要的庫:
import numpy as np
  1. 創(chuàng)建一個(gè)包含異常值的數(shù)據(jù)集:
data = np.array([1, 2, 3, 4, 5, 100])
  1. 計(jì)算數(shù)據(jù)集的平均值和標(biāo)準(zhǔn)差:
mean = np.mean(data)
std = np.std(data)
  1. 定義異常值的閾值。通常,可以將閾值設(shè)置為平均值加減3倍標(biāo)準(zhǔn)差:
threshold = 3 * std
  1. 使用NumPy的布爾索引來獲取不在閾值范圍內(nèi)的值:
filtered_data = data[(data >= mean - threshold) & (data <= mean + threshold)]
  1. 打印輸出過濾后的數(shù)據(jù)集:
print(filtered_data)

上述代碼將刪除數(shù)據(jù)集中的異常值,并輸出過濾后的數(shù)據(jù)集。請(qǐng)注意,這只是一種常見的方法,具體的異常值處理方法可能因數(shù)據(jù)集的特性而異。

0