如何从数据集中找到异常值并使用 Z 分数绘制图表
How to find the outliers from the data set and plot using Z score
数据集如下
store id,revenue ,profit
101,779183,281257
101,144829,838451
101,766465,757565
101,353297,261071
101,1615461,275760
102,246731,949229
102,951518,301016
102,444669,430583
代码在下方
import pandas as pd
dummies1 = dummies[['storeid', 'revenue', 'profit']]
cols = list(dummies1.columns)
cols.remove('storeid')
dummies1[cols]
# code to find the z score
for col in cols:
col_zscore = col + '_zscore'
dummies1[col_zscore] = (dummies1[col] - dummies1[col].mean())/dummies1[col].std(ddof=0)
这里需要做散点图,带异常值的箱线图,怎么做
如何找到异常值如下?
假设 threshold is 3
表示 np.abs(z_score) > 阈值将被视为异常值。
根据 z 分数对数据进行切片,您将得到要绘制的数据。如果您只想找到一个变量在哪里是异常值,您可以这样做(例如):
THRESHOLD = 1.5 #nothing > 3 in your example
to_plot = dummies1[(np.abs(dummies1['revenue_zscore']) > THRESHOLD)]
或者如果任一列都可以是离群值,您可以这样做:
to_plot = dummies1[(np.abs(dummies1['revenue_zscore']) > THRESHOLD) |
(np.abs(dummies1['profit_zscore']) > THRESHOLD)]
你对情节不是很具体,但这是一个利用这一点的例子(使用 ~
反转正常点异常值的检测):
fig, ax = plt.subplots(figsize=(7,5))
non_outliers = dummies1[~((np.abs(dummies1['revenue_zscore']) > THRESHOLD) |
(np.abs(dummies1['profit_zscore']) > THRESHOLD))]
outliers = dummies1[((np.abs(dummies1['revenue_zscore']) > THRESHOLD) |
(np.abs(dummies1['profit_zscore']) > THRESHOLD))]
ax.scatter(non_outliers['revenue'],non_outliers['profit'])
ax.scatter(outliers['revenue'],outliers['profit'], color='red', marker='x')
ax.set_ylabel('Profit')
ax.set_xlabel('Revenue')
数据集如下
store id,revenue ,profit
101,779183,281257
101,144829,838451
101,766465,757565
101,353297,261071
101,1615461,275760
102,246731,949229
102,951518,301016
102,444669,430583
代码在下方
import pandas as pd
dummies1 = dummies[['storeid', 'revenue', 'profit']]
cols = list(dummies1.columns)
cols.remove('storeid')
dummies1[cols]
# code to find the z score
for col in cols:
col_zscore = col + '_zscore'
dummies1[col_zscore] = (dummies1[col] - dummies1[col].mean())/dummies1[col].std(ddof=0)
这里需要做散点图,带异常值的箱线图,怎么做
如何找到异常值如下?
假设 threshold is 3
表示 np.abs(z_score) > 阈值将被视为异常值。
根据 z 分数对数据进行切片,您将得到要绘制的数据。如果您只想找到一个变量在哪里是异常值,您可以这样做(例如):
THRESHOLD = 1.5 #nothing > 3 in your example
to_plot = dummies1[(np.abs(dummies1['revenue_zscore']) > THRESHOLD)]
或者如果任一列都可以是离群值,您可以这样做:
to_plot = dummies1[(np.abs(dummies1['revenue_zscore']) > THRESHOLD) |
(np.abs(dummies1['profit_zscore']) > THRESHOLD)]
你对情节不是很具体,但这是一个利用这一点的例子(使用 ~
反转正常点异常值的检测):
fig, ax = plt.subplots(figsize=(7,5))
non_outliers = dummies1[~((np.abs(dummies1['revenue_zscore']) > THRESHOLD) |
(np.abs(dummies1['profit_zscore']) > THRESHOLD))]
outliers = dummies1[((np.abs(dummies1['revenue_zscore']) > THRESHOLD) |
(np.abs(dummies1['profit_zscore']) > THRESHOLD))]
ax.scatter(non_outliers['revenue'],non_outliers['profit'])
ax.scatter(outliers['revenue'],outliers['profit'], color='red', marker='x')
ax.set_ylabel('Profit')
ax.set_xlabel('Revenue')