Optimus
Optimus

Reputation: 57

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

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.

Upvotes: 2

Views: 4728

Answers (3)

ASH
ASH

Reputation: 20302

How about this?

# importing pandas as pd
import pandas as pd
 
# Creating the dataframe
df=pd.DataFrame({"A":[5,3,None,4],
                 "B":[None,2,4,3],
                 "C":[4,3,8,5],
                 "D":[5,4,2,None]})
 
# Print the dataframe
df

enter image description here

Then.

df = df.ffill(axis = 0)
df

enter image description here

Upvotes: 1

user2736738
user2736738

Reputation: 30926

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')

Upvotes: 2

scima96
scima96

Reputation: 383

You need Pandas ffill():

df.ffill()

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

Upvotes: 5

Related Questions