小技巧4:已知 year 和 dayofyear,怎么转 datetime?
原 DataFrame
d = {"year": [2019, 2019, 2020],"day_of_year": [350, 365, 1]}
df = pd.DataFrame(d)
df
打印结果:
year day_of_year
0 2019 350
1 2019 365
2 2020 1
转 datetime 的 trick
步骤 1: 创建整数
df["int_number"] = df["year"]*1000 + df["day_of_year"]
打印 df 结果:
year day_of_year int_number
0 2019 350 2019350
1 2019 365 2019365
2 2020 1 2020001
步骤 2: to_datetime
df["date"]=pd.to_datetime(df["int_number"],
format = "%Y%j")
注意 "%Y%j" 中转化格式 j
打印结果:
year day_of_year int_number date
0 2019350 2019350 2019-12-16
1 2019365 2019365 2019-12-31
2 20201 2020001 2020-01-01
大家在看
AI安装教程
AI本地安装教程
微软AI大模型通识教程
微软AI大模型通识教程
AI大模型入门教程
AI大模型入门教程
Python入门教程
Python入门教程
Python进阶教程
Python进阶教程
Python小例子200道练习题
Python小例子200道练习题
Python练手项目
Python练手项目
Python从零在线练习题
Python从零到一60题