Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythjon/pandas: how to forward fill from specific value within a group

Tags:

python

pandas

I data in a pandas dataframe looking like this:

      dummy group
0       0    A1
1       0    A1
2       0    A1
3       1    A1
4       0    A1
5       0    A1
6       0    B2
7       0    B1
8       0    B2
9       0    B2
10      0    B2
11      0    B2

I am trying to fill the rest of the values for A1 from the first 1, with additional ones. It is pretty straight forward using the ffill to get rid of NaN, but I could really use some help on this conditional filling. Thanks

EDIT:

the result should look like:

      dummy group
0       0    A1
1       0    A1
2       0    A1
3       1    A1
4       1    A1
5       1    A1
6       0    B2
7       0    B1
8       0    B2
9       0    B2
10      0    B2
11      0    B2
like image 739
user2866103 Avatar asked Nov 28 '25 14:11

user2866103


1 Answers

If I get you right, and you want ones starting from the first one, and only ones and zeros may be present in dummy, then you can use numpy cumsum:

>>> df['dummy'] = df.groupby('group')['dummy'].transform(np.cumsum)
>>> df.ix[df['dummy']!=0, 'dummy'] = 1
>>> df
    dummy group
0       0    A1
1       0    A1
2       0    A1
3       1    A1
4       1    A1
5       1    A1
6       0    B2
7       0    B1
8       0    B2
9       0    B2
10      0    B2
11      0    B2

[12 rows x 2 columns]
like image 50
alko Avatar answered Nov 30 '25 02:11

alko