首页 > 解决方案 > 如果与之前和之后的差异太大,则丢弃值 - Pandas

问题描述

当与前一个或下一个数据框相差太大时,我想从数据框中删除值。

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

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

我不想放弃这样的条件,< x而是考虑与先前和以下值的百分比变化。

谢谢

标签: pythonpandasdata-munging

解决方案


以下将导致所需的输出:

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]

但这取决于您的用例。


推荐阅读