如何将Pandas中的NaT值替换为指定的12月日期?
替换DataFrame中Datetime列的NaT值为指定12月日期
你可以直接用fillna()方法把所有NaT值替换成你需要的12月日期,步骤如下:
- 先定义目标替换日期(确保是datetime类型):
import pandas as pd # 示例:2023年12月8日零点,你可以换成任意12月的有效日期 target_date = pd.to_datetime('2023-12-08 00:00:00')
- 替换Datetime列中的所有NaT值:
df['Datetime'] = df['Datetime'].fillna(target_date)
如果更习惯用replace(),也可以这么写:
df['Datetime'] = df['Datetime'].replace(pd.NaT, target_date)
注意事项
- 确保目标日期的格式和原Datetime列的格式兼容,避免出现类型不匹配问题;
- 因为你只需要满足月度分析,只要目标日期落在2023年12月内,任意日期都可以,按需调整
target_date即可。
内容的提问来源于stack exchange,提问作者Ramon Araneta
相关产品推荐
相关产品推荐

