2017-09-05 37 views
0

我試圖做一些非常類似於this post。除了我有死的結果,例如1-6,我需要計算所有可能的骰子值。大熊貓條紋計數器

import numpy as np 
import pandas as pd 

data = [5,4,3,6,6,3,5,1,6,6] 
df = pd.DataFrame(data, columns = ["Outcome"]) 
df.head(n=10) 

def f(x): 

    x['c'] = (x['Outcome'] == 6).cumsum() 
    x['a'] = (x['c'] == 1).astype(int) 
    x['b'] = x.groupby('c').cumcount() 

    x['streak'] = x.groupby('c').cumcount() + x['a'] 

    return x 

df = df.groupby('Outcome', sort=False).apply(f) 

print(df.head(n=10)) 

    Outcome c a b streak 
0  5 0 0 0  0 
1  4 0 0 0  0 
2  3 0 0 0  0 
3  6 1 1 0  1 
4  6 2 0 0  0 
5  3 0 0 1  1 
6  5 0 0 1  1 
7  1 0 0 0  0 
8  6 3 0 0  0 
9  6 4 0 0  0 

我的問題是'c'不行爲。每當連線斷裂時它應該「重置」其計數器,否則a和b將不正確。

理想情況下,我想喜歡

def f(x): 
    x['streak'] = x.groupby((x['stat'] != 0).cumsum()).cumcount() + 
        ((x['stat'] != 0).cumsum() == 0).astype(int) 
    return x 

優雅的東西作爲鏈接的帖子建議。

+0

您可以添加所需的輸出嗎? – jezrael

回答

0

如上所述,這裏是cumsumcumcount的解決方案,但不像預期的那樣「優雅」(即不是單線)。

我通過標記的連續值開始,讓「塊」的數字:

In [326]: df['block'] = (df['Outcome'] != df['Outcome'].shift(1)).astype(int).cumsum() 

In [327]: df 
Out[327]: 
    Outcome block 
0  5  1 
1  4  2 
2  3  3 
3  6  4 
4  6  4 
5  3  5 
6  5  6 
7  1  7 
8  6  8 
9  6  8 

因爲我現在當重複值出現,我只需要增量算來,對於每個組知道:

In [328]: df['streak'] = df.groupby('block').cumcount() 

In [329]: df 
Out[329]: 
    Outcome block streak 
0  5  1  0 
1  4  2  0 
2  3  3  0 
3  6  4  0 
4  6  4  1 
5  3  5  0 
6  5  6  0 
7  1  7  0 
8  6  8  0 
9  6  8  1 

如果您想從1開始計數,請隨時在最後一行添加+ 1