0

I have a pandas dataframe like this:

INPUT df:

Student_ID   Subject     Weekly_Feedback
100101         NaN         Excellent: 5
100101         NaN         very good:4
100101       Physics       Good: 3
100101         NaN         Excellent: 5
100102         NaN         Excellent: 5
100102       Chemistry     Good: 3
100102         NaN         Good: 3
100102         NaN         very Good: 3
100102         NaN         Needs improvement: 2

I want to fill the rows in Subject column which has NaN values by its corresponding Subject by using Student_ID.

Expected OUTPUT df:

Student_ID   Subject     Weekly_Feedback
100101       Physics      Excellent: 5
100101       Physics      very good:4
100101       Physics      Good: 3
100101       Physics      Excellent: 5
100102       Chemistry    Excellent: 5
100102       Chemistry    Good: 3
100102       Chemistry    Good: 3
100102       Chemistry    very Good: 3
100102       Chemistry    Needs improvement: 2
Ranyk
  • 255
  • 1
  • 8
  • 2
    Use groupby and then a lambda function to apply `ffill` and `bfill` per group: `df['Subject'] = df.groupby("Student_ID")['Subject'].apply(lambda x: x.ffill().bfill())` – anky Dec 22 '20 at 12:38
  • 1
    `df['Subject'] = df.groupby('Student_ID')['Subject'].ffill().bfill()` – David Erickson Dec 22 '20 at 12:38

0 Answers0