2017-05-31 55 views
1

我的代碼檢測時間序列中的異常值。我想要做的是將第一個數據幀列中的異常值替換爲以前的值,這不是異常值。用前一個替換pandas dataframe列中的值

此代碼只是檢測離羣值,創建布爾陣列,其中:

  • True意味着,在數據幀的值是異常值
  • False意味着,在數據幀的值不是異常值
series = read_csv('horario_completo.csv', header=None, squeeze=True) 
df=pd.DataFrame(series) 
from pandas import rolling_median 

consumos=df.iloc[:,0] 
df['rolling_median'] = rolling_median(consumos, window=48, center=True).fillna(method='bfill').fillna(method='ffill') 
threshold =50 
difference = np.abs(consumos - df['rolling_median']) 
outlier = difference > threshold 

到目前爲止,一切正常。

我已經想好了下一個步驟是創建一個面具與同列的前值來取代True值(如果這是可能的,這將是比讓一個循環更快)。

我會試着用一個小例子來解釋它:

這是我有:

index consumo 

    0  54 
    1  67 
    2  98 


index outlier 

    0 False 
    1 False 
    2 True 

而這正是我想做的事:

index consumo 

    0  54 
    1  67 
    2  67 

我認爲我應該創建一個這樣的面具:

df.mask(outlier, df.columns=[[0]][i-1],axis=1) 

顯然這不是寫它的方法。這只是一個解釋,我認爲它可以完成(我正在談論[i-1])。

回答

1

看來你需要shift

consumo = consumo.mask(outlier, consumo.shift()) 
print (consumo) 
0 54.0 
1 67.0 
2 67.0 
Name: consumo, dtype: float64 

最後,如果所有值都ints添加astype

consumo = consumo.mask(outlier, consumo.shift()).astype(int) 
print (consumo) 
0 54 
1 67 
2 67 
Name: consumo, dtype: int32 
+0

我不知道轉移的存在,並()。這真的很有用。你的答案很清楚,效果很好。非常感謝你。 – Jvr

+0

很高興可以幫助,美好的一天! – jezrael

相關問題