user2340706
user2340706

Reputation: 371

iterative append previous value in python

I have the following dataframe:

       Date    A   B  
 =====================
 2015-01-01    A   0
 2015-01-02    A   1
 2015-01-03    A   0
 2015-01-01    B   0
 2015-01-02    B   0
 2015-01-03    B   0
 2015-01-04    B   1
 2015-01-05    B   1

Require:

       Date    A   B       C
 ===========================
 2015-01-01    A   0       0
 2015-01-02    A   1      01
 2015-01-03    A   0     010
 2015-01-01    B   0       0
 2015-01-02    B   0      00
 2015-01-03    B   0     000
 2015-01-04    B   1    0001
 2015-01-05    B   1   00011

Column C is derived for 2015-01-03 by taking previous value of B.

This is the best I got so far, but it appends all values within a group. Previous attempts with shifting wasn't successful for me.

df2 = df.groupby('Date', 'A')['B'].apply(''.join).reset_index()
df = df.merge(df2, on=['Date', 'A'], how='left')

Upvotes: 1

Views: 41

Answers (1)

Vaishali
Vaishali

Reputation: 38415

Try

df1['C'] = df1.groupby('A').B.apply(lambda x: x.astype(str).cumsum())


    Date        A   B   C
0   2015-01-01  A   0   0
1   2015-01-02  A   1   01
2   2015-01-03  A   0   010
3   2015-01-01  B   0   0
4   2015-01-02  B   0   00
5   2015-01-03  B   0   000
6   2015-01-04  B   1   0001
7   2015-01-05  B   1   00011

Upvotes: 5

Related Questions