Question: I am new to Pandas. I have a Pandas data frame like so:

```
df = pd.DataFrame(data={'id': [1, 1, 1, 2, 2, 2, 2], 'val1': [0, 1, 0, 0, 1, 0, 0]})

```

I want to add a column `val2`, that indicates whether an row falls below another row having the same `id` as itself where `val1 == 1`.

The result would be a data frame like:

```
df = pd.DataFrame(data={'id': [1, 1, 1, 2, 2, 2, 2], 'val1': [0, 1, 0, 0, 1, 0, 0], 'val2': [0, 0, 1, 0, 0, 1, 1]})

```

My first thought was to use an apply statement, but these only go by row. And from my experience for loops are never the answer. Any help would be greatly appreciated!

Answer: 
Let's try `shift` + `cumsum` inside a `groupby`.

```
df['val2'] = df.groupby('id').val1.apply(
    lambda x: x.shift().cumsum()
).ge(1).astype(int)

```

Or, in an attempt to avoid the `lambda`,

```
df['val2'] = (    
   df.groupby('id')
     .val1.shift()
     .groupby(df.id)
     .cumsum()
     .ge(1)
     .astype(int)
)

```

```
df
   id  val1  val2
0   1     0     0
1   1     1     0
2   1     0     1
3   2     0     0
4   2     1     0
5   2     0     1
6   2     0     1

```
Using `groupby` + `transform`. Similar to coldspeed's but using `bool` conversion for non-zero `cumsum` values.

```
df['val2'] = df.groupby('id')['val1'].transform(lambda x: x.cumsum().shift())\
                                     .fillna(0).astype(bool).astype(int)

print(df)

   id  val1  val2
0   1     0     0
1   1     1     0
2   1     0     1
3   2     0     0
4   2     1     0
5   2     0     1
6   2     0     1

```