如何在Python中用第95和第5个百分位数替换离群值?

时间:2019-08-21 13:38:30

标签: python pandas dataframe time-series outliers

我正在尝试对我的时间序列数据进行离群值处理,在该数据中,我想将> 95%的值替换为95%的值,将<5%的值替换为5%的值。我已经准备了一些代码,但找不到所需的结果。

我正在尝试使用名为Cut的子函数创建OutlierTreatment函数。代码在下面给出

def outliertreatment(df,high_limit,low_limit):
    df_temp=df['y'].apply(cut,high_limit,low_limit, extra_kw=1)
    return df_temp
def cut(column,high_limit,low_limit):
    conds = [column > np.percentile(column, high_limit),
             column < np.percentile(column, low_limit)]
    choices = [np.percentile(column, high_limit),
            np.percentile(column, low_limit)]
    return np.select(conds,choices,column)  

我希望在OutlierTreatment函数中发送数据帧,其中95作为high_limit和5作为low_limit。如何达到预期的效果?

2 个答案:

答案 0 :(得分:5)

我不确定这种方法是否适合处理异常值,但是为了实现所需的功能,clip函数很有用。它将边界外的值分配给边界值。您可以在documentation中阅读更多内容。

data=pd.Series(np.random.randn(100))
data.clip(lower=data.quantile(0.05), upper=data.quantile(0.95))

答案 1 :(得分:0)

如果您的数据包含多列

对于单个列

p_05 = df['sales'].quantile(0.05) # 5th quantile
p_95 = df['sales'].quantile(0.95) # 95th quantile

df['sales'].clip(p_05, p_95, inplace=True)

对于多个数字列:

num_col = df.select_dtypes(include=['int64','float64']).columns.tolist()

# or you can create a custom list of numerical columns

df[num_col] = df[num_col].apply(lambda x: x.clip(*x.quantile([0.05, 0.95])))

奖励:

使用箱线图检查异常值

import matplotlib.pyplot as plt

for x in num_col:
    df[num_col].boxplot(x)
    plt.figure()