1

I have been looking for a way to do this but haven't been successful in finding something that will work in python/pandas.

I am looking to loop through rows until a 1 is found again and concatenate the previous rows until the one is found and place that in a third column.

For Example:

df

'A'  'B'  'C'
 1    4    4
 2    3    43
 3    1    431
 4    2    4312
 1    5    5
 2    4    54
 1    2    2
 2    2    22
 3    4    224

df
if df['A'] == 1
   df['C'] = df.concat['B']
else 
   df['C'] = df.concat['B'] + df.concat['B'+1]

If you can't tell, this is my first time trying to write a loop.

Any help generating column C from columns A and B using python code would be well appreciated.

Thank you, James

3
  • Please post your current coding based solution. We can help you out with any problems with the code as a reference. Commented Apr 21, 2018 at 3:38
  • Thank you Rann, I appreciate the help. I apologize for my beginner level coding conundrum. Commented Apr 21, 2018 at 3:45
  • Happy to help buddy. Good luck and welcome to StackOverflow. Commented Apr 21, 2018 at 3:51

1 Answer 1

1

This can achieve what you need , create a new key by using cumsum, then we groupby the key we created , using cumsum again

df.groupby(df.A.eq(1).cumsum()).B.apply(lambda x : x.astype(str).cumsum())
Out[838]: 
0       4
1      43
2     431
3    4312
4       5
5      54
6       2
7      22
8     224
Name: B, dtype: object
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! This worked, you are the best, Wen, thank you!
@jimmym91 yw : -) happy coding

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.