我目前正在尝试使用中位数绝对偏差方法从数据集中删除异常值。
为此,我按照@tanemaki在Detect and exclude outliers in Pandas data frame中给出的说明进行操作,该操作可以删除包含至少一个异常值的整个行。
在我链接的帖子中,提出了相同的问题,但未得到回答。
问题是我只希望在单个列中搜索异常值。
例如,我的数据框看起来像:
Temperature Date
1 24.72 2.3
2 25.76 4.6
3 25.42 7.0
4 40.31 9.3
5 26.21 15.6
6 26.59 17.9
例如,数据中有两个'异常:
所以,我想要的是异常值函数仅“注意”“温度”列中的异常,并删除其对应的行。
我正在使用的异常代码是:
df=pd.read_excel(r'/home/.../myfile.xlsx')
from scipy import stats
df[pd.isnull(df)]=0
dfn=df[(np.abs(stats.zscore(df))<4).all(axis=1)] #@taneski
print(dfn)
并且我得到的数据框当前看起来像:
Temperature Date
1 24.72 2.3
2 25.76 4.6
3 25.42 7.0
6 26.59 17.9
如果我没有传达我的信息,则期望的输出将是:
Temperature Date
1 24.72 2.3
2 25.76 4.6
3 25.42 7.0
5 26.21 15.6
6 26.59 17.9
任何指针都会有很大帮助。谢谢!
您始终可以只在stats.zscore
列而不是整个Temperature
上限制df
操作。也许像这样:
In [573]: dfn = df[(np.abs(stats.zscore(df['Temperature']))<4)]
In [574]: dfn
Out[574]:
Temperature Date
1 24.72 2.3
2 25.76 4.6
3 25.42 7.0
5 26.21 15.6
6 26.59 17.9
目前,您正在为整个数据帧计算zscore,然后使用那些计算出的分数过滤数据帧;您想要做的就是将相同的想法应用于一列。
代替
dfn=df[(np.abs(stats.zscore(df))<4).all(axis=1)]
您想拥有
df[np.abs(stats.zscore(df["Temperature"])) < 4]
作为旁注,我发现无法通过将zscores与4进行比较来获得示例结果;我不得不将其切换为2。