Python Pandas 数据帧 将儒略日列转换为日期列

Python Pandas Dataframe convert julian day column to date column

提问人:Mainland 提问时间:10/24/2023 最后编辑:Mainland 更新时间:10/24/2023 访问量:76

问:

我有一个专栏,里面装满了朱利安的日子。我想将它们转换为日期格式。

df1.shape()
(638765, 94)

df1['DAY'] = 
0         2022216 # Format = year (2022),day of the year (216)
1         2022216
2         2022216
3         2022216
4         2022216

from datetime import datetime

解决方案-1:

%timeit df1['Date'] = df1['DAY'].apply(lambda x: datetime.strptime('%d'%x,'%Y%j').strftime('%Y-%m-%d'))
11.9 s ± 50.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
0        2022-08-04
1        2022-08-04
2        2022-08-04
3        2022-08-04
4        2022-08-04

解决方案-2:

%timeit df1['Date'] = pd.to_datetime(df1['DAY'], format='%Y%j')

20.3 ms ± 243 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
0        2022-08-04
1        2022-08-04
2        2022-08-04
3        2022-08-04
4        2022-08-04

我非常喜欢上面的解决方案-2,因为它需要不到一秒钟的时间,而另一个解决方案大约需要 11 秒。我的问题是:即使我没有指定它,这也是将给定的儒略日转换为日期格式('%Y-%m-%d')的默认行为吗?to_datetime

Python Pandas 数据帧 datetime julian-date

评论

1赞 FObersteiner 10/24/2023
不确定我是否理解你的问题 - 你确实指定了,不是吗?此外,执行速度的差异也就不足为奇了。内置的 pandas 经过优化,可以与 pandas 一起使用,而本质上是一个迭代(在 Python 中 - 在大多数情况下很慢!),它调用另一个库(vanilla Python datetime),并且需要从 Python 的 datetime 转换为 pandas datetime 数据类型。从本质上讲,如果你想让 Python 脚本变得快,你就不想在 Python 中做繁重的工作。format='%Y%j'to_datetimeapply
0赞 Mainland 10/24/2023
@FObersteiner我的意思是,我没有在代码中指定输出格式,即.我没有提到它。自动做到了,这也是我想要的。'%Y-%m-%d'
0赞 FObersteiner 10/24/2023
我明白了,所以由于两种情况下的结果(apply 和 to_datetime)都是数据类型 datetime 的列,因此只有在转换为字符串时才能更改格式(显示方式),例如.这就是你要找的吗?.dt.strftime("%b %d %Y")

答:

1赞 Timeless 10/24/2023 #1

这只是一个巧合。

在第一个解决方案中,您 strftime 到格式,碰巧函数 to_datetime(您在第二解决方案中使用的)返回具有相同格式的 a。这是因为“%Y-%m-%d”是后者的默认格式"%Y-%m-%d"DatetimeIndex

在后台,你的儒略日的转换是由 _box_as_indexlike 处理的(在处理的最后),这个转换一个 numpy 数组,该数组保存解析的日期时间:DatetimeIndex

#1 the input :
array([2022216, 2022216, 2022216, 2022216, 2022216], dtype=object)

#2 `array_stptime` gives :
array(['2022-08-04T00:00:00.000000000', '2022-08-04T00:00:00.000000000',
       '2022-08-04T00:00:00.000000000', '2022-08-04T00:00:00.000000000',
       '2022-08-04T00:00:00.000000000'], dtype='datetime64[ns]')

#3 `_box_as_indexlike` gives :
DatetimeIndex(['2022-08-04', '2022-08-04', '2022-08-04', '2022-08-04',
               '2022-08-04'], dtype='datetime64[ns]', freq=None)

评论

1赞 Timeless 10/24/2023
注意:您的第 1 个和第 2 个解决方案会产生两种不同的 dtype:和 。object/stringsdatetime64[ns]
1赞 FObersteiner 10/24/2023
好吧,OP比我想象的还要复杂;没有向右滚动查看strftime ^^