【问题标题】:How to replace the outliers with the 95th and 5th percentile in Python?如何用 Python 中的第 95 和第 5 个百分位替换异常值?
【发布时间】:2019-12-26 19:32:13
【问题描述】:

我正在尝试对我的时间序列数据进行异常值处理,我想用第 95 个百分位数替换 > 95% 的值,用第 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。如何达到预期的效果?

【问题讨论】:

  • 请注意如何设置第 95 和第 5 个值,因为如果您进行迭代,只要超过第 95 个的值发生变化,这些限制就会发生变化。除此之外,只需定义一个函数,如果值高于固定的第 95 位,则将其替换为该数字,如果低于第 5 位,则将其替换为该值?

标签: python pandas dataframe time-series outliers


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您的数据包含多列

    单个列

    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()
    

    【讨论】:

      猜你喜欢
      • 2012-10-31
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2023-02-24
      • 2023-03-27
      • 2021-02-07
      • 2017-09-15
      • 2021-01-12
      相关资源
      最近更新 更多