-1

I have a DataFrame which i need to group by it and add a column based on group by result.

i can able to do groupby but i need a new column named "CLASS" where if the result of groupby "FIRST" column has "3" means it should have PASS else FAIL.

Attached pic for more clarity.

df = pd.DataFrame({'Name': {0: 'Ram',
  1: 'Ram',
  2: 'Ram',
  3: 'Vignesh',
  4: 'Vignesh',
  5: 'Vignesh',
  6: 'Paul',
  7: 'Paul',
  8: 'Paul',
  9: 'Stephen',
  10: 'Stephen',
  11: 'Stephen',
  12: 'Jones',
  13: 'Jones',
  14: 'Jones'},
 'Section': {0: 'A',
  1: 'A',
  2: 'A',
  3: 'B',
  4: 'B',
  5: 'B',
  6: 'C',
  7: 'C',
  8: 'C',
  9: 'D',
  10: 'D',
  11: 'D',
  12: 'E',
  13: 'E',
  14: 'E'},
 'School': {0: 'Don Bosco',
  1: 'Don Bosco',
  2: 'Don Bosco',
  3: 'Don Bosco',
  4: 'Don Bosco',
  5: 'Don Bosco',
  6: 'Don Bosco',
  7: 'Don Bosco',
  8: 'Don Bosco',
  9: 'Don Bosco',
  10: 'Don Bosco',
  11: 'Don Bosco',
  12: 'Don Bosco',
  13: 'Don Bosco',
  14: 'Don Bosco'},
 'Rank': {0: 'First',
  1: 'Second',
  2: 'First',
  3: 'Second',
  4: 'Second',
  5: 'First',
  6: 'First',
  7: 'First',
  8: 'First',
  9: 'Second',
  10: 'Second',
  11: 'Second',
  12: 'First',
  13: 'First',
  14: 'First'}})
newdf = df.groupby(['Name', 'Section','School','Rank']).size().unstack(fill_value=0)

Actual DataFrame

enter image description here

Actual output: What i tried.

enter image description here

Expected output with class column based on above condition.

Expected output

Sathish Kumar
  • 39
  • 1
  • 5

2 Answers2

0

You can use numpy.where:

import numpy as np

newdf['Class'] = np.where(newdf.First.eq(3), 'PASS', 'FAIL')
Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
0

An easy option would be this:

import numpy as np

newdf['Class'] = np.where(newdf['First'] >= 3, 'PASS', 'FAIL')
Hoter
  • 155
  • 1
  • 7