简体   繁体   中英

Change or Fill dataframe cell based on condition by group

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM