0
Year Month score1 score2 score3
2022 Jan 98 NaN 100
feb NaN 39 NaN
2021 sept 100 50 NaN
nov 100 NaN 76
dec 100 52 NaN

(apologies idk how to make a dataframe in this text editor) I created a pivot table with indexes = ['year','month'] and I want to forward fill just score3, but only within the index. How can I get my dataframe to look like:

Year Month score1 score2 score3
2022 Jan 98 NaN 100
feb NaN 39 100
2021 sept 100 50 NaN
nov 100 NaN 76
dec 100 52 76
lost
  • 3
  • 2
  • The pandas tag wiki contains a link to a canonical question about how to create reproducible dataframes – Paul H Mar 15 '23 at 03:35

1 Answers1

1

You can probably use groupby.ffill:

df['score3'] = df['score3'].groupby(level='Year').ffill()

Or, for a more generic way:

cols = ['score3']
df[cols] = df.groupby(level='Year')[cols].ffill()
mozway
  • 194,879
  • 13
  • 39
  • 75