移除异常值(+/- 3 std)并在Python / pandas中替换为np.nan - python

我已经看到几种接近解决我问题的解决方案

link1
link2

但到目前为止,他们并没有帮助我成功。

我相信以下解决方案是我所需要的,但仍然会出现错误(并且我没有信誉点对此进行评论/提问):link

(我收到以下错误,但在管理以下命令.copy()时,我不知道在inplace=True或在何处添加“ df2=df.groupby('install_site').transform(replace)”:

SettingWithCopyWarning:
试图在DataFrame的切片副本上设置一个值。
尝试改用.loc[row_indexer,col_indexer] = value

请参阅文档中的警告:link

所以,我试图提出自己的版本,但我一直陷于困境。开始。

我有一个按时间索引的数据框,其中包含站点列(许多不同站点的字符串值)和浮点值。

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函数选项的原因。

python大神给出的解决方案

如果我理解正确,则无需遍历各列。该解决方案用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))