简体   繁体   中英

Pandas Dataframe Assign Value Using Previous N Row Value

This is my pandas dataframe.

Status   
index                                    
2011-01-10 16:00:00  Active
2011-01-11 16:00:00  
2011-01-12 16:00:00  Inactive
2011-01-13 16:00:00  
2011-01-14 16:00:00     
2011-01-18 16:00:00

I would like to fill the blank value of the column 'Status' using previous N row value. The result look like following.

Status   
index                                    
2011-01-10 16:00:00  Active
2011-01-11 16:00:00  Active
2011-01-12 16:00:00  Inactive
2011-01-13 16:00:00  Inactive
2011-01-14 16:00:00  Inactive   
2011-01-18 16:00:00  Inactive

What's the best way to do?

if the rows are already null, then forward fill should be sufficient:

  df.ffill()

if the rows are empty string, then replace with np.nan, and forward fill:

  df.replace('',np.nan).ffill()


                       status
 index  
2011-01-10 16:00:00    Active
2011-01-11 16:00:00    Active
2011-01-12 16:00:00    Inactive
2011-01-13 16:00:00    Inactive
2011-01-14 16:00:00    Inactive
2011-01-18 16:00:00    Inactive

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