如何将Pandas DataFrame中的日期列转换为年积日
解决方法
首先确保你的raw_time列是Pandas的datetime类型,如果读入时未自动解析,先执行转换:
import pandas as pd # 假设你的DataFrame名为df df['raw_time'] = pd.to_datetime(df['raw_time'])
接下来直接提取年积日,生成目标列day_of_year:
df['day_of_year'] = df['raw_time'].dt.dayofyear
如果只需要保留索引和day_of_year列,可执行:
result_df = df[['day_of_year']]
验证结果
针对你提供的样例数据,执行后会得到:
index day_of_year 1429029 3 1429030 3 1429031 3 1429032 2 1429033 2 1429034 2 1429035 2 1429036 2 1429037 2 1429038 2 1429039 2 1429040 2 1429041 2 1429042 2 1429043 2 1429044 2
说明:Pandas的dt.dayofyear会自动处理闰年(比如1992年是闰年),且同一自然日的所有时间会返回相同的年积日数值,完全匹配你的需求。
内容的提问来源于stack exchange,提问作者user2100039
相关产品推荐
相关产品推荐

