使用标准差剔除异常值
创作时间:
作者:
@小白创作中心
使用标准差剔除异常值
引用
CSDN
1.
https://blog.csdn.net/u014217137/article/details/143819886
在数据分析和处理过程中,异常值的处理是一个重要的环节。异常值可能会对后续的分析和建模产生负面影响,因此需要在数据预处理阶段进行合理的处理。本文将介绍如何使用标准差的方法来剔除异常值,并通过Python代码实现这一过程。
方法
在绘制图表之前对数据进行预处理,剔除掉那些波动很大的数据点。我们可以使用一些统计方法来识别和剔除这些异常值。常用的方法包括使用标准差(Standard Deviation)或四分位数(Interquartile Range, IQR)来检测和剔除异常值。本文将重点介绍使用标准差的方法。
示例代码
下面是一个完整的示例代码,展示了如何读取数据、进行数据清洗、分段读取数据并绘图。
数据读取与清洗
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
# 读取数据
file_path = 'step_rewards.txt'
data = pd.read_csv(file_path, header=None, names=['reward'])
# 检查数据结构
print(data.head())
# 数据清洗 - 使用标准差方法剔除异常值
def remove_outliers(df, column, threshold=3):
mean = df[column].mean()
std = df[column].std()
outliers = (df[column] - mean).abs() > threshold * std
return df[~outliers]
# 清洗数据
cleaned_data = remove_outliers(data, 'reward')
# 打印前几行查看清洗后的数据
print(cleaned_data.head())
分段读取数据并绘图
# 将清洗后的数据保存到新的文件中
output_file_path = 'filter_step_rewards.txt'
cleaned_data.to_csv(output_file_path, index=False, header=False)
print(f"Filtered data saved to {output_file_path}")
# 确保输出目录存在
output_dir = 'plots'
os.makedirs(output_dir, exist_ok=True)
# 每隔 10000 行提取数据
chunk_size = 10000
num_chunks = len(cleaned_data) // chunk_size
for i in range(num_chunks):
start_idx = i * chunk_size
end_idx = (i + 1) * chunk_size
chunk = cleaned_data.iloc[start_idx:end_idx]
# 绘制清洗后的数据
plt.figure(figsize=(10, 6))
plt.plot(chunk.index, chunk['reward'], label='Cleaned Reward')
plt.legend()
plt.title(f'Rewards for Chunk {i+1}')
plt.xlabel('Step')
plt.ylabel('Reward')
# 保存图像
image_path = os.path.join(output_dir, f'reward_chunk_{i+1}.png')
plt.savefig(image_path)
plt.close()
print(f"Generated {num_chunks} plots and saved them in {output_dir}")
代码解释
数据读取:
data = pd.read_csv(file_path, header=None, names=['reward'])
这行代码读取
step_rewards.txt
文件,文件没有标题行。我们将列名指定为reward
。数据检查:
print(data.head())
打印数据的前几行,以便确认数据是否正确加载。
数据清洗:
def remove_outliers(df, column, threshold=3): mean = df[column].mean() std = df[column].std() outliers = (df[column] - mean).abs() > threshold * std return df[~outliers]
remove_outliers
函数用于剔除异常值。它计算数据的均值和标准差,然后将距离均值超过threshold
倍标准差的数据点标记为异常值。threshold
参数默认为3,表示剔除距离均值超过3倍标准差的数据点。可以根据实际情况调整这个阈值。
调用cleaned_data = remove_outliers(data, 'reward')
remove_outliers
函数对数据进行清洗。
- 保存清洗后的数据:
output_file_path = 'filter_step_rewards.txt' cleaned_data.to_csv(output_file_path, index=False, header=False) print(f"Filtered data saved to {output_file_path}")
- 将清洗后的数据保存到
filter_step_rewards.txt
文件中。 index=False
表示不保存索引。header=False
表示不保存列名。
- 分段读取数据并绘图:
chunk_size = 10000 num_chunks = len(cleaned_data) // chunk_size for i in range(num_chunks): start_idx = i * chunk_size end_idx = (i + 1) * chunk_size chunk = cleaned_data.iloc[start_idx:end_idx] plt.figure(figsize=(10, 6)) plt.plot(chunk.index, chunk['reward'], label='Cleaned Reward') plt.legend() plt.title(f'Rewards for Chunk {i+1}') plt.xlabel('Step') plt.ylabel('Reward') image_path = os.path.join(output_dir, f'reward_chunk_{i+1}.png') plt.savefig(image_path) plt.close()
chunk_size
定义了每组数据的大小。num_chunks
计算总共有多少组数据。for
循环遍历每组数据,提取并绘制清洗后的数据。plt.savefig(image_path)
将图像保存到指定路径。plt.close()
关闭当前图像,防止内存泄漏。
- 输出信息:
输出生成的图像数量和保存路径。print(f"Generated {num_chunks} plots and saved them in {output_dir}")
运行上述代码后,将在plots
目录中找到10张图像文件,每张图像对应一组数据的清洗后奖励值的图表。
关于异常值的处理
- 在
remove_outliers
函数中,我们定义了一个布尔 Seriesoutliers
,用于标识哪些数据点是异常值。outliers = (df[column] - mean).abs() > threshold * std
(df[column] - mean).abs()
:计算每个数据点与均值的绝对差值。> threshold * std
:判断绝对差值是否大于threshold
倍的标准差。- 结果是一个布尔 Series,其中
True
表示该数据点是异常值,False
表示该数据点不是异常值。
~outliers
在 Python 中,~
是按位取反运算符。对于布尔值,~True
为False
,~False
为True
。因此,~outliers
会将布尔 Seriesoutliers
中的True
变为False
,False
变为True
。df[~outliers]
df[~outliers]
是 Pandas 中的一种索引操作,用于从 DataFrame 中选择符合条件的行。具体来说:
df[~outliers]
会选择outliers
中为False
的行,即非异常值的行。- 结果是一个新的 DataFrame,其中不包含任何异常值。
结果展示
热门推荐
一元二次方程根与系数的秘密:韦达定理揭示的奇妙关系
孟姜女哭长城:一座血泪浇筑的文化丰碑
茉莉花适合在室内养吗
"二人三足"与生肖的关联:羊与猪的性格解读
二人三足打一生肖:揭秘生肖背后的趣味知识
如何计算贷款利率:法律领域的专业解析与实务指南
狗咬尾巴是怎么回事
养生茶饮用指南:探讨凉茶与热茶的健康影响及适宜饮用方式
陈皮的功效与应用:从传统到现代的全面解析
2025快速有效追讨债务的方法有哪些?
降低论文重复率的实用指南:从引用到改写全方位提升原创性
沪锡期货涨跌因素分析四个要点!
解读沪锡指数:构成、意义及市场趋势分析
《致命魔术》电影赏析:揭秘19世纪末伦敦魔术师的致命对决
花卉品种图及名称大全:500种花卉详解及82种家庭常养花卉指南
如何联系图片作者获取版权授权
如何通过技术创新提高500mm宽中置柜KYN500的可靠性?
手麻是什么意思怎么回事
单招考生务必精选复习资料,避免盲目搜集
武安舍利塔:巍巍古塔,屹立千年
比比东,凭借什么才能成为众人的意难平?
手脚麻木的原因与应对策略:健康警示与生活习惯调整
喉咙被烫伤疼痛怎么办?全面指南助你快速恢复
贵州传来“龙吟”?历史上龙其实并不少见,那么专家如何解释
计算机零基础知识
CBA上座率排名出炉!辽宁夺冠,山西紧随其后,广东意外未入前五
四大名著作者们的诗词水平谁高谁低?其中一人完胜
中国最适合自驾游的10大好去处,国内自驾游十大目的地排行榜
上海至昆明自驾游终极指南:路线规划、必玩景点、食宿建议及安全注意事项
尿蛋白弱阳性说明什么