2

I have a following dataframe:

      A    label
0    1.0     a
1    2.0     a
2    3.0     a
3    NaN     a
4    NaN     a
5    NaN     a
6    9.0     a
7    8.0     a
8    7.0     a
9    NaN     a
10   NaN     a
11  21.0     a
12  32.0     a
13  12.0     a

I want to fill nan values in the column A as follow:

Fill null values at index 3,4 and 5: by taking average of values at index 2 and 6 i.e. (3+9)/2.

Fill null values at index 9 and 10: by taking average of values at index 8 and 11 i.e. (7+21)/2.

And similarly for all other null values in the dataframe, if occurs. I have spent a lot of time thinking about the precise solution, but couldn't find one. How can I do that?

1 Answer 1

3

Use forward filling of missing values, add back filling of misisng values and last divide by 2 for mean:

df['A'] = df.A.ffill().add(df.A.bfill()).div(2)
print (df)
       A label
0    1.0     a
1    2.0     a
2    3.0     a
3    6.0     a
4    6.0     a
5    6.0     a
6    9.0     a
7    8.0     a
8    7.0     a
9   14.0     a
10  14.0     a
11  21.0     a
12  32.0     a
13  12.0     a

Details:

print (df.assign(ffill = df.A.ffill(),
                 bfill = df.A.bfill(),
                 both  = df.A.ffill().add(df.A.bfill()),
                 fin = df.A.ffill().add(df.A.bfill()).div(2)))
       A label  ffill  bfill  both   fin
0    1.0     a    1.0    1.0   2.0   1.0
1    2.0     a    2.0    2.0   4.0   2.0
2    3.0     a    3.0    3.0   6.0   3.0
3    NaN     a    3.0    9.0  12.0   6.0
4    NaN     a    3.0    9.0  12.0   6.0
5    NaN     a    3.0    9.0  12.0   6.0
6    9.0     a    9.0    9.0  18.0   9.0
7    8.0     a    8.0    8.0  16.0   8.0
8    7.0     a    7.0    7.0  14.0   7.0
9    NaN     a    7.0   21.0  28.0  14.0
10   NaN     a    7.0   21.0  28.0  14.0
11  21.0     a   21.0   21.0  42.0  21.0
12  32.0     a   32.0   32.0  64.0  32.0
13  12.0     a   12.0   12.0  24.0  12.0
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.