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
1
  • df.groupby('name').value.ffill() Commented Oct 3, 2018 at 17:08

1 Answer 1

0

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

df["value"] = df.groupby(["name"])["value"].fillna(method="ffill")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.