请使用 Python 实现一个函数,该函数能够自动检测数据中的异常值,并根据不同的分布类型(如正态分布、偏态分布)选择适当的处理方法。

import numpy as np
import pandas as pd
from scipy import stats

def detect_and_handle_outliers(data, distribution_type='normal', method='iqr', threshold=1.5):
    """
    检测并处理数据中的异常值。

    参数:
    - data: 输入数据,可以是列表、NumPy 数组或 Pandas Series。
    - distribution_type: 分布类型,支持 'normal' (正态分布) 和 'skewed' (偏态分布)。
    - method: 检测异常值的方法,支持 'iqr' (四分位距法) 和 'zscore' (Z 分数法)。
    - threshold: 阈值,用于调整异常值的检测灵敏度。

    返回:
    - 处理后的数据 (Pandas Series)。
    """
    # 转换为 Pandas Series 以方便处理
    if not isinstance(data, pd.Series):
        data = pd.Series(data)

    # 检测异常值
    outliers_mask = None

    if distribution_type == 'normal' and method == 'zscore':
        # 正态分布 + Z 分数法
        z_scores = np.abs(stats.zscore(data))
        outliers_mask = z_scores > threshold

    elif distribution_type == 'normal' and method == 'iqr':
        # 正态分布 + 四分位距法 (效果类似于 Z 分数法,但更稳健)
        q1 = data.quantile(0.25)
        q3 = data.quantile(0.75)
        iqr = q3 - q1
        lower_bound = q1 - threshold * iqr
        upper_bound = q3 + threshold * iqr
        outliers_mask = (data < lower_bound) | (data > upper_bound)

    elif distribution_type == 'skewed' and method == 'iqr':
        # 偏态分布 + 四分位距法 (推荐用于偏态数据)
        q1 = data.quantile(0.25)
        q3 = data.quantile(0.75)
        iqr = q3 - q1
        lower_bound = q1 - threshold * iqr
        upper_bound = q3 + threshold * iqr
        outliers_mask = (data < lower_bound) | (data > upper_bound)

    else:
        raise ValueError("不支持的分布类型或方法")

    # 处理异常值
    if outliers_mask is not None:
        # 用中位数替换异常值 (适用于正态分布)
        if distribution_type == 'normal':
            data[outliers_mask] = data.median()
        # 用边界值替换异常值 (适用于偏态分布)
        elif distribution_type == 'skewed':
            lower_bound = data.quantile(0.05)  # 5% 分位数
            upper_bound = data.quantile(0.95)  # 95% 分位数
            data[data < lower_bound] = lower_bound
            data[data > upper_bound] = upper_bound

    return data


# 示例 1: 正态分布数据 + Z 分数法
normal_data = np.random.normal(0, 1, 1000)  # 生成正态分布数据
processed_data = detect_and_handle_outliers(normal_data, distribution_type='normal', method='zscore')
print("处理后的正态分布数据示例:", processed_data.head())

# 示例 2: 偏态分布数据 + 四分位距法
skewed_data = np.random.exponential(1, 1000)  # 生成指数分布数据 (偏态)
processed_data = detect_and_handle_outliers(skewed_data, distribution_type='skewed', method='iqr')
print("处理后的偏态分布数据示例:", processed_data.head())

实现解析

  1. 输入数据转换:将输入数据转换为 Pandas Series,方便后续处理。
  2. 异常值检测:
    • 对正态分布数据,支持 Z 分数法 (zscore) 和四分位距法 (iqr)。
    • 对偏态分布数据,推荐使用四分位距法 (iqr),避免 Z 分数法的假设问题。
  3. 异常值处理:
    • 正态分布:用中位数替换异常值。
    • 偏态分布:用 5% 和 95% 分位数的边界值替换异常值。

示例说明

  • 正态分布数据:假设数据服从正态分布,使用 Z 分数法检测异常值后,用中位数填充。
  • 偏态分布数据:假设数据右偏,使用四分位距法检测异常值后,用边界值填充。

注意事项

  • 分布类型需根据实际情况选择,否则可能导致处理效果不佳。
  • 阈值 (threshold) 可根据数据特点调整,默认为 1.5 是一个常用值。