Anagha Anagha - 8 days ago 6
Python Question

Repeat the value in column B until there is change occur in column A in python

I'm new to python and have a query. I need the value repeated in column B until a change occur in column A.

Here's the sample Data:

A B
18 1
18 0
18 0
24 2
24 0
24 0
24 0
10 3
10 0
10 0


How I want my output

Column A Column B
18 1
18 1
18 1
18 1
24 2
24 2
10 3
10 3
10 3
10 3


Please help me thru this. Thank you

Answer

You can use transform by first if need repeat first value of each group:

df['Column B'] = df.groupby('Column A')['Column B'].transform('first')
print (df)
   Column A  Column B
0        18         1
1        18         1
2        18         1
3        18         1
4        24         2
5        24         2
6        10         3
7        10         3
8        10         3
9        10         3

Another solution which dont depends of Column A - replace 0 values by NaN, use forward filling by ffill and last cast to int:

df['Column B'] = df['Column B'].replace(0,np.nan).ffill().astype(int)
print (df)
   Column A  Column B
0        18         1
1        18         1
2        18         1
3        18         1
4        24         2
5        24         2
6        10         3
7        10         3
8        10         3
9        10         3