Home > Blockchain >  Fill blank cells in Pandas dataframe with value from cell above it
Fill blank cells in Pandas dataframe with value from cell above it

Time:05-06

Consider a situation.

A    B    C
1    X    Park
2    Y    
3    Z    Team
4    L
5    M    Cycle
6    K    
7    N    

Expected output:

A    B    C
1    X    Park
2    Y    Park
3    Z    Team
4    L    Team
5    M    Cycle
6    K    Cycle
7    N    Cycle

There are millions of rows so can not be done manually. Gaps between empty cells and cells with values can be more than 1000s of rows in column C.

CodePudding user response:

You need Pandas ffill():

df.ffill()

See the pandas documentation for parameters: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.ffill.html

CodePudding user response:

Once you have NaN values for empty locations (this way you are specifically targetting the empty locations)

df[df[0]==""] = np.NaN

you can do this (In case you already have NaN in those location you can directly use this method. I mentioned this way since whenever we read from a CSV file or something, those empty portions comes blank)

df.fillna(method='ffill')
  • Related