How to create a new column in df and to use shift function?

I have the following df:

data = {'Counter':list(range(1, 10)),
        'Country':['USA','UK','UK','USA','UK','USA','UK','USA','UK'],
        'A':[0,0,1,1,1,1,1,1,1]

       }

df=pd.DataFrame(data)
print(df)

   Counter Country  A
0        1     USA  0
1        2      UK  0
2        3      UK  1
3        4     USA  1
4        5      UK  1
5        6     USA  1
6        7      UK  1
7        8     USA  1
8        9      UK  1

I would like to create a new column that will be a cumulative sum of column A. I’ve tried this solution but it doesn’t work:

df["B"]=0
df["B"]=df["A"] + df["B"].shift(1)
print(df)

   Counter Country  A    B
0        1     USA  0  NaN
1        2      UK  0  0.0
2        3      UK  1  1.0
3        4     USA  1  1.0
4        5      UK  1  1.0
5        6     USA  1  1.0
6        7      UK  1  1.0
7        8     USA  1  1.0
8        9      UK  1  1.0

I know that I can solve it by using cumsum function but is there any way to solve it by using shift(1)?

Thanks.

Answer

You could try with list comprehension:

df['B'] = [sum(df['A'][:i]) for i, v in enumerate(df['A'], 1)]

And now:

print(df)

Is:

   Counter Country  A  B
0        1     USA  0  0
1        2      UK  0  0
2        3      UK  1  1
3        4     USA  1  2
4        5      UK  1  3
5        6     USA  1  4
6        7      UK  1  5
7        8     USA  1  6
8        9      UK  1  7