Nadello
Nadello

Reputation: 13

Pandas(Python) : How to fill empty cells with previous row value with conditions

For order dataset where Customer name (Name) per order are not repeated and some order does not have customer name. Example :

enter image description here

How can I make the name is repeated like :

enter image description here

I wonder if it's still possible to use ffill() with condition that order id should be the same

Upvotes: 0

Views: 1737

Answers (3)

Muhammad Mehran
Muhammad Mehran

Reputation: 17

You can use this

DataFrame.fillna(method="ffill", axis=1, limit=1)

Upvotes: 0

Andreas Bauer
Andreas Bauer

Reputation: 66

You have to use groupby and then fill. If you want to apply the fill operation only on the "Name" column, it should look like this:

import pandas as pd
import numpy as np
data = {"order_id": [1,1,2,3], "name":["adam", np.nan, np.nan, "Su"],"total":            [15,np.nan, 5, 10]}
df = pd.DataFrame(data)
df["name"] = df.groupby("order_id")["name"].fillna(method='ffill')

Upvotes: 1

Suhas Mucherla
Suhas Mucherla

Reputation: 1413

Try:

df=pd.DataFrame({'order id':['A1','A1','A2','A3'],'Name':['Adam',np.nan,np.nan,'su']})
df['Name']=df['Name'].groupby(df['order id']).fillna(method='ffill')

df
Out[28]: 
  order id  Name
0       A1  Adam
1       A1  Adam
2       A2   NaN
3       A3    su

Upvotes: 0

Related Questions