jimmym91
jimmym91

Reputation: 13

Concatenating by looping through rows in Python

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

Upvotes: 1

Views: 106

Answers (1)

BENY
BENY

Reputation: 323226

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

Upvotes: 1

Related Questions