Thanuja
Thanuja

Reputation: 23

How to fill the nulls with conditions in python?

I have a Dataframe

import pandas as pd
import numpy as np

df = pd.DataFrame(np.nan, index=range(1,19), columns=['A','B','C','D','E','F','G','H'])

a = [1550, 41, 9.41, 22.6, 4.74, 3.2, 11.64, 2.23]
b = [1540, 43, 9.41, 22.3, 4.84, 3.12, 11.64, 2.23]
c = [1590, 39, 9.41, 23.7, 4.74, 3.0, 11.64, 2.23]
d = [1540, 41, 9.41, 22.5, 4.74, 3.2, 11.64, 2.23]
e = [1580, 32, 9.27, 22.8, 4.82, 2.7,  12.2, 2.50]
f = [1550, 30, 9.00,  20,  4.50,  2.5,  10,   2.00]

df.loc[[1,8,13,15,16,18],:] = [a,b,c,d,e,f]

Looking like this

    A        B       C       D        E     F         G     H
1   1550.0  41.0    9.41    22.6    4.74    3.20    11.64   2.23
2   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
3   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
4   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
5   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
6   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
7   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
8   1540.0  43.0    9.41    22.3    4.84    3.12    11.64   2.23
9   NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
10  NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
11  NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
12  NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
13  1590.0  39.0    9.41    23.7    4.74    3.00    11.64   2.23
14  NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
15  1540.0  41.0    9.41    22.5    4.74    3.20    11.64   2.23
16  1580.0  32.0    9.27    22.8    4.82    2.70    12.20   2.50
17  NaN     NaN     NaN     NaN     NaN     NaN     NaN     NaN
18  1550.0  30.0    9.00    20.0    4.50    2.50    10.00   2.00

The null values in 2,3,4,5,6,7 should be filled with Average(1st row, 8th row)

The null values in 9,10,11,12 should be filled with Average(8th row and 13th row)

The null value in the 14th row should be filled with Average(13th row and 15th row)

The null value in the 17th row should be filled with Average(16th row and 18th row)

I have a data frame with 5000 rows. I want nulls to be filled in this manner.

Upvotes: 0

Views: 52

Answers (1)

BENY
BENY

Reputation: 323226

You can try ffill + bfill, then take the average

df = (df.ffill()+df.bfill())/2

Upvotes: 5

Related Questions