[英]Count valuable (more than n times) repetitions of a pandas time series
我想計算我的系列中每個階段的時間。 對於階段,我的意思是連續 1 或 0 的重復次數,例如:
rng = pd.date_range('2015-02-24', periods=15, freq='T')
s = pd.Series([0,1,1,1,0,0,1,0,1,0,1,1,1,1,0],index=rng)
我想作為 output:
phase0 -> zeros:1 minute, ones:3 minutes,
pahse1 -> zeros:6 minutes, ones:4 minutes,
etc
在這種情況下,值 >= 大於 3。
我可以通過以下方式以低重復率刪除 1:
index_to_remove=s.groupby((s.shift() != s).cumsum()).filter(lambda x: len(x) < 3).index
現在我可以在原始時間序列中將該索引處的元素設為等於 0。
s[index_to_remove]=0
錯過的是計算每個階段的分鍾數。
有人可以幫助我嗎? 我對一種聰明的方式很感興趣。 我對我到目前為止所使用的東西並不感到驕傲,所以如果你能給我一個更好的方法,我將不勝感激。
謝謝你們
*** 我知道我應該使用s.diff()
並且當這個新的時間序列從 1 到 -1 是一個階段,而它從 -1 到 1 是一個零階段
我認為您需要聚合min
和max
,獲取差異,轉換為分鍾並添加 1 分鍾並重塑為 DataFrame:
#faster solution for set 0 by length per groups
m=s.groupby((s.shift() != s).cumsum()).transform('size') < 3
s[m]=0
#create groups for 0,1 pairs
res = (s.eq(0) & s.shift().eq(1)).cumsum()
print (res)
df = s.index.to_series().groupby([res, s]).agg(['min','max'])
df = (df['max'].sub(df['min'])
.dt.total_seconds()
.div(60)
.add(1)
.unstack(fill_value=0)
.astype(int)
.rename_axis('phase'))
print (df)
0 1
phase
0 1 3
1 6 4
2 1 0
*** 這是我找到的最佳解決方案:
from itertools import groupby
groups = groupby(s)
result = [(label, sum(1 for _ in group)) for label, group in groups]
但我無法處理將 0 和 1 組合在一起的事實
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.