Forward fill an indexed dataframe, but only forward fill per value in index

59 views Asked by At
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
1

There are 1 answers

2
mozway On

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()