2017-09-15 1 views
2

Étant donné une trame de données pandas, je souhaite exclure les lignes correspondant aux valeurs aberrantes (valeur Z = 3) en fonction de l'une des colonnes.Pandas dataframe - supprimer les valeurs aberrantes

Le dataframe ressemble à ceci:

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 

Pour la ligne:

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

L'exception suivante est soulevée:

-------------------------------------------------------------------------  
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' 

Et la valeur de retour de

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

est

True 

Pourquoi ai-je l'exception ci-dessus, et comment puis-je exclure les valeurs aberrantes?

Répondre

2

Utilisez ce booléen chaque fois que vous avez ce genre de problème:

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 
0

Je crois que vous pouvez créer un filtre booléen avec les valeurs aberrantes puis sélectionnez le oposite de celui-ci.

outliers = stats.zscore(df['_source.price']).apply(lambda x: np.abs(x) == 3) 
df_without_outliers = df[~outliers]