python - Pandas 数据框 - 删除异常值

标签 python pandas scipy

<分区>

给定一个 pandas 数据框,我想根据其中一列排除与异常值(Z 值 = 3)对应的行。

数据框看起来像这样:

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

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

最佳答案

如果要使用 Interquartile Range给定数据集的(即 IQR,如下面的 Wikipedia image 所示)( 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

关于python - Pandas 数据框 - 删除异常值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46245035/

相关文章:

Python3 : How to convert plain html into nested dictionary based on level of `h` tags?

python - TCP 套接字未连接 [WinError 10060] - Python

python - cars.iloc[[3, 0]]、cars.iloc[[3]、[0]] 和 cars.iloc[3, 0] 之间的区别

python - 转置数据框更改列名称

python - Scipy 多元正常 : How to draw deterministic samples?

python - 将 Python 模块命名为 "global"或其他关键字是否不好?

python - 将 utc 时间字符串转换为 unix 时间戳

python - 将条件列添加到多级列数据框中

python - 使用自制 Python 在 Mac 10.8 上安装 scipy 的正确位置是什么?

python - 在 Python 中计算 Kullback–Leibler 散度的有效方法