python - 如果与之前和之后的差异太大,则丢弃值 - Pandas
问题描述
当与前一个或下一个数据框相差太大时,我想从数据框中删除值。
df = pd.DataFrame({'Watt':[554, 557, 51, 480, 601, 458, 19, 492, 503, 22, 399]})
例如,在这里我需要删除 (51, 19, 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]
但这取决于您的用例。
推荐阅读
- sql-server - T-SQL - XML 路径子句不返回结果集
- unity3d - “...”中的着色器错误:内核“...”中“...”的未知参数类型 (39)
- javascript - codeigniter 在按钮单击和显示时启动计时器
- vue.js - 传统网站如何搭建Vue(jquery替换)
- c++ - GCC STL 是否具有从 typedef 别名获取原始类型的特征?
- javascript - JS奇数之和迷路了?
- python - 防止私有和基于 pypi 的 Python 包之间的命名空间冲突
- comparison-operators - 比较 gdscript 中的浮点数时,运算符“<”中的操作数“bool”和“float”无效
- android - 在应用程序启动时自动调用库函数
- swift - Swift 数据类型列表