0

I have a dataframe like the following, where I have for certain names (A and C) a value the first month of the year .

df
     date      name   value
0   201601       A     3
1   201607       A    NaN
2   201612       A    NaN
3   201601       B    NaN
4   201607       B    NaN
5   201612       B    NaN
6   201601       C     7
7   201607       C    NaN
8   201612       C    NaN

For this names I want to replace NaN with the value of the first month of the year. While for the names I do not have this information I would like to keep the NaN value. At the end I would like a dataframe like the following.

df
     date      name   value
0   201601       A     3
1   201607       A     3
2   201612       A     3
3   201601       B    NaN
4   201607       B    NaN
5   201612       B    NaN
6   201601       C     7
7   201607       C     7
8   201612       C     7
emax
  • 6,965
  • 19
  • 74
  • 141

1 Answers1

0

You can try something like this, it will fill forward based on your groups

df["value"] = df.groupby(["name"])["value"].fillna(method="ffill")
Sven Harris
  • 2,884
  • 1
  • 10
  • 20