简体   繁体   中英

How to backfill NaN values based on condition that next valid value after NaN is equal to previous valid value

Here is an excerpt from my pandas DataFrame:

df =
TransactionId   Value   AuthenticationId
1214050         8243.12 AE19D686
NaN             8243.12 AE19D686
NaN             8243.12 AE19D686
NaN             8243.12 AE19D686
NaN             8243.12 AE19D686
1214050         8243.12 AE19D686

I want to backfill any NaN values that meet the condition that the current valid (ie not NaN) TransactionId is equal to the previous valid value (first row in the df).

You can check if ffill and bfill are consistent, then apply back-filling conditionally via pd.DataFrame.loc :

bfilled = df['TransactionId'].bfill()

df.loc[df['TransactionId'].ffill() == bfilled, 'TransactionId'] = bfilled

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