Count values that go in row in group?

Viewed 45

I have two dataframes:

id     val
a      w
a      w
a      l
a      w
b      w
b      w
b      w
c      w
c      l
d      w
d      w
d      w
d      w

I want to get ids which had 3 w in row in column val. So desired result must be:

id 
b      
d      

As you see only ids b and d had at least 3 w in column val in row. How to do that?

1 Answers

Not the fastest solution but here:

import pandas as pd
import re # regular expression matching

df = <your_dataframe>

ids = [i for i in df.id.unique() if re.search('w{3}', ''.join(df[df.id==i].val))]

w{3} means look for 3 consecutive 'w's

Edit: Without Regex

import pandas as pd

df = pd.DataFrame({
    "id": ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd', 'd', 'd'], 
    "val": ['w', 'w', 'l', 'w', 'w', 'w', 'w', 'w', 'l', 'w', 'w', 'w', 'w']
    })

def threeInRow(values, match='w'):
    count = 0
    for i in range(len(values)):
        if(values[i] == match):
            count += 1
        else:
            count = 0
        # "if three in a row, exit early"
        if(count >= 3):
            return True
    return False

ids = [i for i in df.id.unique() if threeInRow(list(df[df.id==i].val)) ]
Related