auto fill column Python pandas with dependent increment

In a given column "a" I have values 0 and 1 and I want to create a second column "b" so that it looks like this:

| "a" | "b" |
| --- | --- |
| 0 | 0 |
| 0 | 0 |
| 1 | 1 |
| 0 | 1 |
| 0 | 1 |
| 0 | 1 |
| 0 | 1 |
| 1 | 2 |
| 0 | 2 |
| 0 | 2 |
| 1 | 3 |
| 0 | 3 |
| 1 | 4 |
| 0 | 4 |
| 0 | 4 |
|...|...|

1 answer

  • answered 2021-04-20 15:55 Scott Boston

    Use, df['B'] = df['A'].cumsum()

    Given, df = pd.DataFrame({'A':[0,0,1,0,0,0,0,1,0,0,1,0,1,0,0]})

    Output:

        A  B
    0   0  0
    1   0  0
    2   1  1
    3   0  1
    4   0  1
    5   0  1
    6   0  1
    7   1  2
    8   0  2
    9   0  2
    10  1  3
    11  0  3
    12  1  4
    13  0  4
    14  0  4