python - 在散点图上标记异常值
问题描述
我有一个如下所示的数据框:
print(df.head(10))
day CO2
1 549.500000
2 663.541667
3 830.416667
4 799.695652
5 813.850000
6 769.583333
7 681.941176
8 653.333333
9 845.666667
10 436.086957
然后,我使用以下函数和代码行从 CO2 列中获取 ouliers:
def estimate_gaussian(dataset):
mu = np.mean(dataset)#moyenne cf mu
sigma = np.std(dataset)#écart_type/standard deviation
limit = sigma * 1.5
min_threshold = mu - limit
max_threshold = mu + limit
return mu, sigma, min_threshold, max_threshold
mu, sigma, min_threshold, max_threshold = estimate_gaussian(df['CO2'].values)
condition1 = (dataset < min_threshold)
condition2 = (dataset > max_threshold)
outliers1 = np.extract(condition1, dataset)
outliers2 = np.extract(condition2, dataset)
outliers = np.concatenate((outliers1, outliers2), axis=0)
这给了我以下结果:
print(outliers)
[830.41666667 799.69565217 813.85 769.58333333 845.66666667]
现在我想在散点图上用红色标记那些异常值。
您可以在下面找到到目前为止我用来在散点图上将单个异常值标记为红色的代码,但我找不到为异常值列表的每个元素(即 numpy.ndarray)执行此操作的方法:
y = df['CO2']
x = df['day']
col = np.where(x<0,'k',np.where(y<845.66666667,'b','r'))
plt.scatter(x, y, c=col, s=5, linewidth=3)
plt.show()
这是我得到的,但我想要所有 ouliers 的相同结果。请你帮助我好吗?
解决方案
这是一个快速的解决方案:
我将重新创建您已经开始的内容。您只共享了数据框的头部,但无论如何,我只是插入了一些随机异常值。看起来您的“estimate_gaussian()”函数只能返回两个异常值?
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame([549.500000,
50.0000000,
830.416667,
799.695652,
1200.00000,
769.583333,
681.941176,
1300.00000,
845.666667,
436.086957],
columns=['CO2'],
index=list(range(1,11)))
def estimate_gaussian(dataset):
mu = np.mean(dataset) # moyenne cf mu
sigma = np.std(dataset) # écart_type/standard deviation
limit = sigma * 1.5
min_threshold = mu - limit
max_threshold = mu + limit
return mu, sigma, min_threshold, max_threshold
mu, sigma, min_threshold, max_threshold = estimate_gaussian(df.values)
condition1 = (df < min_threshold)
condition2 = (df > max_threshold)
outliers1 = np.extract(condition1, df)
outliers2 = np.extract(condition2, df)
outliers = np.concatenate((outliers1, outliers2), axis=0)
然后我们将绘制:
df_red = df[df.values==outliers]
plt.scatter(df.index,df.values)
plt.scatter(df_red.index,df_red.values,c='red')
plt.show()
如果您需要更细微的东西,请告诉我!
推荐阅读
- android - 无法将 java.lang.string 转换为 json 对象
- javascript - Twitter API 应用程序身份验证,CORS 问题
- ios - Adobe Animate 缺少出口合规性 ITSAppUsesNonExemptEncryption False
- angular - 日期无效 - “MM/YYYY”字符串到日期转换时出错
- node.js - 为什么 npm start 会忽略参数中转义的反引号?
- struct - Julia:我们可以在不可变结构类型中更改多少对象?
- localization - 翻译 DNN 2sxc 模块中的内容时出错
- javascript - JSP 属性 JSON 对象在 Javascript 中丢弃转义字符
- webforms - 如何调试 DNN 中的视图状态验证错误?
- c++ - 从文件读取后没有得到任何输出