Home > Net >  Change or Fill dataframe cell based on condition by group
Change or Fill dataframe cell based on condition by group

Time:02-01

Original DF:

Group    Col_A    Day
 A        0        1
 A        0        2
 A        0        3
 A        1        4
 A        1        5
 A        1        6
 A        1        7
 B        0        1
 B        0        2
 B        0        3
 B        1        4
 B        1        5
 B        0        6
 B        1        7

What I need to do is, by group, change values in Col_A from 0 to 1 in instances where a value of 0 follows a value of 1. In this simple example, this occurs in group B on Day 6.

Desired DF:

Group    Col_A    Day
 A        0        1
 A        0        2
 A        0        3
 A        1        4
 A        1        5
 A        1        6
 A        1        7
 B        0        1
 B        0        2
 B        0        3
 B        1        4
 B        1        5
 B        1        6
 B        1        7

My actual dataframe has thousands of groups and several more columns, FYI. Any suggestions is appreciated.

CodePudding user response:

If you want to change all 0s following a 1 to 1, then you can use groupby_cummax:

df['Col_A'] = df.groupby('Group')['Col_A'].cummax()

Output:

   Group  Col_A  Day
0      A      0    1
1      A      0    2
2      A      0    3
3      A      1    4
4      A      1    5
5      A      1    6
6      A      1    7
7      B      0    1
8      B      0    2
9      B      0    3
10     B      1    4
11     B      1    5
12     B      1    6
13     B      1    7

CodePudding user response:

Use df.loc[df.groupby('Group')['Col_A'].diff().eq(-1), 'Col_A'] = 1.

  •  Tags:  
  • Related