Pandas数据框架 - 去除异常值

4

我希望能够通过一个列的值,排除Z值为3的离群值,针对pandas数据框进行操作。

数据框长这样:

df.dtypes
_id                   object
_index                object
_score                object
_source.address       object
_source.district      object
_source.price        float64
_source.roomCount    float64
_source.size         float64
_type                 object
sort                  object
priceSquareMeter     float64
dtype: object

针对以下代码行:

dff=df[(np.abs(stats.zscore(df)) < 3).all(axis='_source.price')]

以下异常被触发:
-------------------------------------------------------------------------    
TypeError                                 Traceback (most recent call last)
<ipython-input-68-02fb15620e33> in <module>()
----> 1 dff=df[(np.abs(stats.zscore(df)) < 3).all(axis='_source.price')]

/opt/anaconda3/lib/python3.6/site-packages/scipy/stats/stats.py in zscore(a, axis, ddof)
   2239     """
   2240     a = np.asanyarray(a)
-> 2241     mns = a.mean(axis=axis)
   2242     sstd = a.std(axis=axis, ddof=ddof)
   2243     if axis and mns.ndim < a.ndim:

/opt/anaconda3/lib/python3.6/site-packages/numpy/core/_methods.py in _mean(a, axis, dtype, out, keepdims)
     68             is_float16_result = True
     69 
---> 70     ret = umr_sum(arr, axis, dtype, out, keepdims)
     71     if isinstance(ret, mu.ndarray):
     72         ret = um.true_divide(

TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

而且,

返回值为

np.isreal(df['_source.price']).all()

True

为什么会出现上述异常,如何排除异常值?
3个回答

13

如果想要使用给定数据集的四分位距(即IQR,如下所示的维基百科图片)(Ref):

def Remove_Outlier_Indices(df):
    Q1 = df.quantile(0.25)
    Q3 = df.quantile(0.75)
    IQR = Q3 - Q1
    trueList = ~((df < (Q1 - 1.5 * IQR)) |(df > (Q3 + 1.5 * IQR)))
    return trueList

基于上述去除函数,可以根据数据集的统计内容获得异常值子集:

# Arbitrary Dataset for the Example
df = pd.DataFrame({'Data':np.random.normal(size=200)})

# Index List of Non-Outliers
nonOutlierList = Remove_Outlier_Indices(df)

# Non-Outlier Subset of the Given Dataset
dfSubset = df[nonOutlierList]

interquartile range


正是我所需要的。点赞。谢谢。 - Chocksmith
1
对于那些想要同时将此应用于多个定量列(Data1、Data2等)的人,请添加.all(1):dfSubset = df[nonOutlierList.all(1)] - vpvinc

4

每当您遇到这种问题时,请使用此布尔值:

df=pd.DataFrame({'Data':np.random.normal(size=200)})  #example 
df[np.abs(df.Data-df.Data.mean())<=(3*df.Data.std())] #keep only the ones that are within +3 to -3 standard deviations in the column 'Data'.
df[~(np.abs(df.Data-df.Data.mean())>(3*df.Data.std()))] #or the other way around

AttributeError: 'DataFrame' object has no attribute 'Data' - Nairum
1
@Nairum Data 是正在访问的 df 的列。它需要更改以适应您要检测异常值的特定 DataFrame 的实际列。 - B-Schmidt

2
我认为您可以使用布尔筛选器筛选异常值,然后选择其相反值。
outliers = stats.zscore(df['_source.price']).apply(lambda x: np.abs(x) == 3)
df_without_outliers = df[~outliers]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接