简体   繁体   中英

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:

在此处输入图像描述

How can I make the name is repeated like:

在此处输入图像描述

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

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

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

You can use this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM