Skip to content
Advertisement

conditional groupby and update column – python, pandas, groupby

i have a df which I want to add a column that shows the student who is place (1) from the group(‘subject’, ‘class’) and update the column after there is a new place (1).

code:

JavaScript
╔═════════╦═════════╦═════════╦═══════╗
║ subject ║  class  ║ student ║ place ║
╠═════════╬═════════╬═════════╬═══════╣
║ eng     ║ Class_4 ║ henry   ║     7 ║
║ math    ║ Class_3 ║ pan     ║     8 ║
║ math    ║ Class_3 ║ larry   ║    10 ║
║ math    ║ Class_3 ║ larry   ║     1 ║
║ math    ║ Class_3 ║ henry   ║     7 ║
║ math    ║ Class_3 ║ larry   ║    10 ║
║ math    ║ Class_3 ║ terry   ║     9 ║
║ math    ║ Class_3 ║ henry   ║     7 ║
║ math    ║ Class_3 ║ henry   ║    11 ║
║ math    ║ Class_3 ║ henry   ║     1 ║
║ math    ║ Class_3 ║ pan     ║    11 ║
║ math    ║ Class_3 ║ pan     ║     3 ║
║ math    ║ Class_3 ║ moose   ║     6 ║
║ eng     ║ Class_4 ║ pan     ║     2 ║
║ eng     ║ Class_4 ║ moose   ║     4 ║
╚═════════╩═════════╩═════════╩═══════╝

result trying to get

╔═════════╦═════════╦═════════╦═══════╦═════════╗
║ subject ║  class  ║ student ║ place ║ new_col ║
╠═════════╬═════════╬═════════╬═══════╬═════════╣
║ eng     ║ Class_4 ║ henry   ║     7 ║ nil     ║
║ math    ║ Class_3 ║ pan     ║     8 ║ nil     ║
║ math    ║ Class_3 ║ larry   ║    10 ║ nil     ║
║ math    ║ Class_3 ║ larry   ║     1 ║ nil     ║
║ math    ║ Class_3 ║ henry   ║     7 ║ larry   ║
║ math    ║ Class_3 ║ larry   ║    10 ║ larry   ║
║ math    ║ Class_3 ║ terry   ║     9 ║ larry   ║
║ math    ║ Class_3 ║ henry   ║     7 ║ larry   ║
║ math    ║ Class_3 ║ henry   ║    11 ║ larry   ║
║ math    ║ Class_3 ║ henry   ║     1 ║ larry   ║
║ math    ║ Class_3 ║ pan     ║    11 ║ henry   ║
║ math    ║ Class_3 ║ pan     ║     3 ║ henry   ║
║ math    ║ Class_3 ║ moose   ║     6 ║ henry   ║
║ eng     ║ Class_4 ║ pan     ║     2 ║ nil     ║
║ eng     ║ Class_4 ║ moose   ║     4 ║ nil     ║
╚═════════╩═════════╩═════════╩═══════╩═════════╝

kindly advise. thank you

Advertisement

Answer

Mask the values in place column which are not equal to 1 then group the masked column by subject and class and use ffill to forward fill the values

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement