用前一个替换 pandas 数据框列中的值

Replace value in a pandas dataframe column by the previous one

我的代码检测时间序列中的异常值。我想要做的是用不是异常值的先前值替换第一个数据框列中的异常值。

此代码仅检测异常值,创建一个布尔数组,其中:

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])。

看来你需要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