我有下面的数据帧df
,其中stamp B
有时为空。必须使用 Stamp A
的日期和 Time
列中的相应时间来填充此类空值
stamp A stamp B Time
0 2012-10-08 18:15:05 2012-10-08 18:15:05 19:00:01
1 2012-10-09 12:15:05 NaT 18:45:09
2 2012-10-11 18:13:00 NaT 12:20:20
3 2012-10-11 08:15:15 2012-10-11 18:15:05 22:10:05
4 2012-10-12 18:15:20 2012-10-12 17:10:20 19:34:12
这是我的解决方案 -
>>>from datetime import dateime as dtm
>>>result = df[df['stamp B'].isnull()].apply(lambda x: dtm.combine(x['stamp A'].date(), dtm.strptime(x["Time"], "%H:%M:%S").time()), axis=1)
它返回结果
如下:
1 2012-10-09 18:45:09
2 2012-10-11 12:20:20
dtype: datetime64[ns]
但不确定如何将此结果
替换为原始数据帧df['stamp B']
中的NaT
值
最佳答案
使用Series.dt.floor
用于删除时间并添加时间增量 to_timedelta
然后将缺失值替换为 Series.combine_first
:
dates = df['stamp A'].dt.floor('d').add(pd.to_timedelta(df['Time']))
df['stamp B'] = df['stamp B'].combine_first(dates)
print (df)
stamp A stamp B Time
0 2012-10-08 18:15:05 2012-10-08 18:15:05 19:00:01
1 2012-10-09 12:15:05 2012-10-09 18:45:09 18:45:09
2 2012-10-11 18:13:00 2012-10-11 12:20:20 12:20:20
3 2012-10-11 08:15:15 2012-10-11 18:15:05 22:10:05
4 2012-10-12 18:15:20 2012-10-12 17:10:20 19:34:12
关于python - Pandas 用 df.apply 结果替换原始列空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61730862/