gpt4 book ai didi

python - 将 cftime.DatetimeJulian 转换为日期时间

转载 作者:行者123 更新时间:2023-12-04 01:10:01 27 4
gpt4 key购买 nike

我正在尝试转换 xarray数据数组到机器学习项目的 Pandas 数据帧,但时间数据似乎在 cftime.DatetimeJulian 中格式,不能使用 pandas 进行转换 to_datetime()方法。建议?谢谢。

nor_xr.time

<xarray.DataArray 'time' (time: 1372)>
array([cftime.DatetimeJulian(2015, 3, 31, 0, 0, 0, 0, 0, 90),
cftime.DatetimeJulian(2018, 12, 31, 0, 0, 0, 0, 6, 365)], dtype=object)
Coordinates:
* time (time) object 2015-03-31 00:00:00 ... 2018-12-31 00:00:00
Attributes:
standard_name: time
axis: T

nor_df = nor_xr.to_dataframe().reset_index()
nor_df.head()

time
0 2015-03-31 00:00:00
1 2015-04-01 00:00:00

pd.to_datetime(nor_df.time)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-104-1f0fc00ad825> in <module>
2
3 #|nor_df.time.unique()
----> 4 pd.to_datetime(nor_df.time)

~\AppData\Local\Continuum\anaconda3A\lib\site-packages\pandas\core\tools\datetimes.py in to_datetime(arg, errors, dayfirst, yearfirst, utc, box, format, exact, unit, infer_datetime_format, origin, cache)
449 else:
450 from pandas import Series
--> 451 values = _convert_listlike(arg._values, True, format)
452 result = Series(values, index=arg.index, name=arg.name)
453 elif isinstance(arg, (ABCDataFrame, MutableMapping)):

~\AppData\Local\Continuum\anaconda3A\lib\site-packages\pandas\core\tools\datetimes.py in _convert_listlike(arg, box, format, name, tz)
366 dayfirst=dayfirst,
367 yearfirst=yearfirst,
--> 368 require_iso8601=require_iso8601
369 )
370

pandas\_libs\tslib.pyx in pandas._libs.tslib.array_to_datetime()

pandas\_libs\tslib.pyx in pandas._libs.tslib.array_to_datetime()

pandas\_libs\tslib.pyx in pandas._libs.tslib.array_to_datetime()

TypeError: <class 'cftime._cftime.DatetimeJulian'> is not convertible to datetime

最佳答案

事实上,这是一个普遍的要求。推荐的做法是拉出索引(a CFTimeIndex )并使用其内置的 to_datetimeindex 方法:

datetimeindex = nor_xr.indexes['time'].to_datetimeindex()

然后您可以更换 CFTimeIndex与其 DatetimeIndex对应:

nor_xr['time'] = datetimeindex

关于python - 将 cftime.DatetimeJulian 转换为日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55786995/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com