0

I have a dataframe that looks like this.

+----+-------+
| ID | Value |
+----+-------+
|  1 | 23    |
|  1 | NA    |
|  1 | NA    |
|  1 | NA    |
|  2 | 24    |
|  2 | NA    |
|  2 | NA    |
+----+-------+

For each ID value in a group, I either have one value or NA. I wanted to apply this non NA value to the NA values in that specific group as below.

Desired Output :

+----+-------+
| ID | Value |
+----+-------+
|  1 | 23    |
|  1 | 23    |
|  1 | 23    |
|  1 | 23    |
|  2 | 24    |
|  2 | 24    |
|  2 | 24    |
+----+-------+

How can we achieve this in pandas?

2
  • 2
    df = df.sort_values(['ID', 'Value']).fffill() Commented Aug 23, 2020 at 16:36
  • This worked. Thanks. Just one change. df = df.sort_values(['ID', 'Value']).ffill() Commented Aug 23, 2020 at 16:53

2 Answers 2

2

Check with

df.Value.fillna(df.groupby('ID').Value.transform('first'), inplace=True)
Sign up to request clarification or add additional context in comments.

2 Comments

Heyy benyo, Good seeing you here. Thanks for your cumsum solution, it really did the trick. ~ And wishing you Happy Coding as well.
@High-Octane happy coding ~
1

say your dataframe variable is df

Then,

df.value.fillna(method='ffill')

Should do the trick.

Documentation for your reference :

Forward Fill Documentation Reference

1 Comment

thanks. RichieV's answer worked for me

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.