1

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')

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

This is nice and succinct :-)
Also you can do df.groupby('A').B.apply(pd.Series.cumsum)
This is great! Thank you @Vaishali

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.