[英]Python, pandas: Cut off filter for spikes in a cumulative series
我有這樣的一系列累積值:
1821, 2015-01-26 22:14:42+02:00, 24574.7
1822, 2015-01-26 22:15:05+02:00, 24574.7
1823, 2015-01-26 22:15:28+02:00, 24574.8
1824, 2015-01-26 22:15:49+02:00, 24574.9
1825, 2015-01-26 22:16:11+02:00, 24574.9
1826, 2015-01-26 22:16:34+02:00, 24576.0
1828, 2015-01-26 22:17:19+02:00, 24575.1
1829, 2015-01-26 22:17:41+02:00, 24575.2
1830, 2015-01-26 22:18:03+02:00, 24575.3
1831, 2015-01-26 22:18:25+02:00, 24575.3
問題在於,有時對於累積的序列,我會得到不正常的值,並且值應該只會增加。 像第1826行一樣(值是24576,下一個較小)。 有沒有辦法從熊貓系列對象中刪除這些值? 即,當一個值大於上一個和下一個值時?
您可以使用np.diff()
計算相鄰差。 只要差異為負,您就知道需要刪除上一行。
這可以通過使用Pandas的布爾索引的單行解決方案來完成。 單行代碼還采用了其他技巧:Pandas的map
和diff
方法以及lambda
函數。 map
用於將lambda
函數應用於所有行。 需要lambda
函數來創建自定義的“少寫”比較,該比較會將NaN值評估為True。
以下示例說明。
免責聲明:僅當我們可以假設每行始終大於或等於前兩個位置的行時,此方法才有效。 換句話說:row [i]> = row [i-2]
import pandas as pd
df = pd.DataFrame({'A':['a','b','c','d','e', 'f', 'g'], 'B': [1,2,2,4,3,5,6]})
# We're going to use Pandas' diff method, telling it to take the difference 1 row back.
print df['B'].diff(1)
# Createa boolean index. We use map and a lambda function to handle the tricky case of the first row evaluating to
print df['B'].diff(1).map(lambda x: not(x<0))
# Here is the one line solution!
# Redefine df to only contain the rows that behave themselves.
df = df[df['B'].diff(1).map(lambda x: not(x<0))]
print df
該diff
有一個內置方法:
In [30]:
pd.concat([df.head(1), df[df['cumulative value'].diff()>=0]])
Out[30]:
timestamp cumulative value
0
1821 2015-01-26 20:14:42 24574.7
1822 2015-01-26 20:15:05 24574.7
1823 2015-01-26 20:15:28 24574.8
1824 2015-01-26 20:15:49 24574.9
1825 2015-01-26 20:16:11 24574.9
1826 2015-01-26 20:16:34 24576.0
1829 2015-01-26 20:17:41 24575.2
1830 2015-01-26 20:18:03 24575.3
1831 2015-01-26 20:18:25 24575.3
指出要在此處調用diff
EDIT會丟失第一行,因此我使用了一個丑陋的技巧,其中我將diff
的結果連接到第一行,所以我不會丟失第一行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.