如何根据 NaN 之后的下一个有效值等于前一个有效值的条件回填 NaN 值

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

这是我的 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

我想回填满足当前有效(即非 NaN)TransactionId 等于先前有效值(df 中的第一行)的条件的任何 NaN 值。

您可以检查ffillbfill是否一致,然后通过pd.DataFrame.loc有条件地应用回填:

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

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