如果与之前和之后的差异太大,则丢弃值 - Pandas

问题描述

我想从数据帧中删除与前一个或下一个差异太大的值。

df = pd.DataFrame({'Watt':[554,557,51,480,601,458,19,492,503,22,399]})

例如,这里我需要删除 (51,22),一种“异常值”。

我不想用 < x 之类的条件删除,而是考虑与前一个和后一个值的百分比变化。

谢谢

解决方法

以下将导致所需的输出:

df = pd.DataFrame({'Watt':[554,557,51,480,601,458,19,492,503,22,399]})
df['previous percent'] = df.Watt/df.Watt.shift(1)
df['next percent'] = df.Watt.shift(-1)/df.Watt

threshold_previous = .8
threshold_next = 2

df[(1-df['previous percent'] < threshold_previous) & 
   (df['next percent']-1 < threshold_next)]

稍微更优雅的解决方案是:

df['average'] = (df.Watt.shift(1) + df.Watt.shift(-1)) / 2
threshold = .8
df[df.Watt/df.average > threshold]

但这取决于您的用例。