[英]Is there a method to aggregate time series in pandas based on the sequential count of an occurrence?
我正在 pandas 中尋找一種方法來計算時間序列中特定值的連續出現次數。
假設我正在進行一項實驗,我擲硬幣並得到正面或反面(1 或 0)。 我將我的結果記錄在 pandas 系列中,我希望看看有多少實例(計數)有兩個連續磁頭、三個連續磁頭、四個連續磁頭等。 此外,我希望它是一種滾動計數,這意味着形式的序列(尾、頭、頭、頭、尾)將返回成對出現的兩個正面實例的計數,以及一個單次計數系列的三個頭。
有沒有一種自然的方法可以使用 Series/DataFrame 中的方法來做到這一點? 我可以用一些 for 循環來做到這一點,但我擔心這樣做的成本。
謝謝。
編輯:請求的輸入/輸出。
輸入:
a = pd.DataFrame({'coin' : [0,1,1,1,0]})
print(a.summary_of_windows())
Output:
{1: 3
2: 2,
3: 1}
output 可以是一個字典:鍵 1 表示出現正面,其中出現了三個。 鍵 2 表示成對的連續磁頭(其中有兩個),鍵 3 表示長度為 3 的磁頭序列(發生一次)。
您可以使用DataFrame.rolling
:
>>> df
coin
0 0
1 1
2 1
3 1
4 0
# Compute how many sequences of two heads there are:
>>> df['coin'].rolling(2).sum().eq(2).sum()
2
# Do it for three sequences:
# remember to change v AND v
>>> df['coin'].rolling(3).sum().eq(3).sum()
1
# Find total number of heads occurences:
>>> df['coin'].sum()
3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.