df的一列,去极值和画频率分布图

67 阅读1分钟

去极值

def depolarize(data:pd.DataFrame,column:str):
    lower_quantile = data[column].quantile(0.025)
    upper_quantile = data[column].quantile(0.975)

    # 筛选出95%分位数区间内的数值
    filtered_hqic = data[(data[column] >= lower_quantile) & 
                                (data[column] <= upper_quantile)]
    return filtered_hqic

画频率分布图

def histogram(data: pd.Series):
    import matplotlib.pyplot as plt
    import numpy as np
    from scipy import stats

    # 假设filtered_hqic是已经存在的DataFrame,并且包含了'1 month model HQIC'列

    # 计算均值和标准差
    mu = data.mean()
    std = data.std()
    # 计算均值和中位数
    mean_hqic = data.mean()
    median_hqic = data.median()


    # 创建主坐标轴并绘制频率分布图
    fig,ax1 = plt.subplots()  # 获取返回的Axes对象
    ax1.hist(data, bins=50, edgecolor='black', alpha=0.7, color='#ffae4c', label='Frequency Distribution')

    # 创建次坐标轴
    ax2 = ax1.twinx()

    # 创建一个数值数组,用于计算分布曲线
    x_values = np.linspace(data.min(), data.max(), 1000)

    # 计算正态分布曲线的y值
    curve = stats.norm.pdf(x_values, mu, std)

    # 在次坐标轴上绘制分布曲线
    ax2.plot(x_values, curve, 'k--', label=f'Normal Distribution ($\mu={mu:.2f}, \sigma={std:.2f})$')
    # 标注均值和中位数
    ax2.axvline(mean_hqic, color='red', linestyle='--', label=f'Mean: {mean_hqic:.2f}')  # 标注均值
    ax2.axvline(median_hqic, color='green', linestyle='-', label=f'Median: {median_hqic:.2f}')  # 标注中位数

    # 设置主坐标轴的标签
    ax1.set_xlabel(data.name)

    # 设置次坐标轴的标签
    ax2.set_ylabel('Probability Density', color='black')

    # 设置图例
    # 设置主坐标轴的图例
    ax1.legend(loc='upper left', frameon=False, fontsize='small', handlelength=1, handletextpad=0.5)

    # 设置次坐标轴的图例
    ax2.legend(loc='upper right', frameon=False, fontsize='small', handlelength=1, handletextpad=0.5)

    # 手动调整图例位置
    # # 例如,将主坐标轴的图例向右移动一些
    # ax1.legend(loc='upper left', bbox_to_anchor=(1, 1))

    # 调整布局
    plt.tight_layout()

    # 显示图表
    plt.show()