I would have suggest you using the method="ffill"
from pandas fillna but your case is more specific. You can add a custom function to do that in a new column as follow :
You have this input as df
dataframe
datetime time1 date time2 x1 x2 x3 x4
0 2023-01-03 08:30:18 01/03/2023 08:30:18 62.95 62.95 62.91 62.92
1 2023-01-03 08:30:19 01/03/2023 08:30:19 62.93 62.94 62.93 62.94
2 2023-01-03 08:30:26 01/03/2023 08:30:20 62.90 62.90 62.89 62.89
3 2023-01-03 08:30:21 01/03/2023 NaN 62.90 62.90 62.89 62.89
4 2023-01-03 08:30:22 01/03/2023 08:30:22 62.91 62.91 62.91 62.91
5 2023-01-03 08:30:23 01/03/2023 08:30:23 62.91 62.92 62.91 62.92
Define the custom function and fill your NaN
:
import datetime
def custom_fill_na(s):
# take specific series as input
formated_time = pd.to_datetime(s, format='%H:%M:%S')
values = []
for i, time in enumerate(formated_time.dt.time):
if time is pd.NaT:
values.append((formated_time[i-1] + datetime.timedelta(seconds=1)).time())
else:
values.append(time)
return values
# Now call the function in new column
df['time3'] = custom_fill_na(df.time2)
print(df)
Output
datetime time1 date time2 x1 x2 x3 x4 time3
0 2023-01-03 08:30:18 01/03/2023 08:30:18 62.95 62.95 62.91 62.92 08:30:18
1 2023-01-03 08:30:19 01/03/2023 08:30:19 62.93 62.94 62.93 62.94 08:30:19
2 2023-01-03 08:30:26 01/03/2023 08:30:20 62.90 62.90 62.89 62.89 08:30:20
3 2023-01-03 08:30:21 01/03/2023 NaN 62.90 62.90 62.89 62.89 08:30:21
4 2023-01-03 08:30:22 01/03/2023 08:30:22 62.91 62.91 62.91 62.91 08:30:22
5 2023-01-03 08:30:23 01/03/2023 08:30:23 62.91 62.92 62.91 62.92 08:30:23
Feel free to replace your column if desired. Hope it helps.