Skip to main content
 首页 » 编程设计

python之用前一个替换 Pandas 数据框列中的值

2024年10月01日7lovecherry

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

这段代码只是检测异常值,创建一个 bool 数组,其中:

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

请您参考如下方法:

看来你需要shift :

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

如果所有值都是 int,最后添加 astype :

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