【问题标题】:Drop value if is too different from the previous and following - Pandas如果与之前和之后的差异太大,则丢弃值 - Pandas
【发布时间】:2021-02-18 10:10:06
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

  • 顺便说一句,为什么应该删除 492?看起来不像异常值。
  • 这是一个错误。坦克

标签: python pandas data-munging


【解决方案1】:

以下将导致所需的输出:

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]

但这取决于您的用例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 2015-11-21
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多