簡體   English   中英

移除異常值(+/- 3 std)並在Python / pandas中替換為np.nan

[英]Remove outliers (+/- 3 std) and replace with np.nan in Python/pandas

我已經看到幾種接近解決我問題的解決方案

鏈接1 鏈接2

但到目前為止,他們並沒有幫助我成功。

我認為以下解決方案是我所需要的,但仍然會出現錯誤(並且我沒有信譽點可對此進行評論/問題): 鏈接

(我收到以下錯誤,但是在管理以下命令df2=df.groupby('install_site').transform(replace)時,我不知道在.copy()或添加“ .copy() inplace=True ”的位置:

SettingWithCopyWarning:試圖在DataFrame的切片副本上設置一個值。 嘗試改用.loc[row_indexer,col_indexer] = value

請參閱文檔中的警告: 鏈接

所以,我試圖提出自己的版本,但我一直陷於困境。 開始。

我有一個按時間索引的數據框,其中包含站點列(許多不同站點的字符串值)和浮點值。

time_index            site       val

我想遍歷“ val”列(按地點分組),並用NaN(每組)替換所有離群值(與平均值相差+/- 3個標准差)。

使用以下函數時,無法使用我的True / Falses向量索引數據幀:

def replace_outliers_with_nan(df, stdvs):
    dfnew=pd.DataFrame()
    for i, col in enumerate(df.sites.unique()):
        dftmp = pd.DataFrame(df[df.sites==col])
        idx = [np.abs(dftmp-dftmp.mean())<=(stdvs*dftmp.std())] #boolean vector of T/F's
        dftmp[idx==False]=np.nan  #this is where the problem lies, I believe
        dfnew[col] = dftmp
    return dfnew

另外,我擔心上面的函數在700萬以上的行上會花費很長時間,這就是為什么我希望使用groupby函數選項的原因。

如果我理解正確,則無需遍歷各列。 該解決方案用NaN替換所有偏差超過三個組標准偏差的所有值。

def replace(group, stds):
    group[np.abs(group - group.mean()) > stds * group.std()] = np.nan
    return group

# df is your DataFrame
df.loc[:, df.columns != group_column] = df.groupby(group_column).transform(lambda g: replace(g, 3))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM