我正在尝试将xarray数据数组转换为机器学习项目的 pandas 数据帧,但时间数据似乎采用一种cftime.DatetimeJulian格式,使用 pandasto_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:00Attributes: standard_name: time axis: Tnor_df = nor_xr.to_dataframe().reset_index()nor_df.head() time0 2015-03-31 00:00:001 2015-04-01 00:00:00pd.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
2 回答
慕尼黑5688855
TA贡献1848条经验 获得超2个赞
事实上,这是一个普遍的要求。推荐的做法是拉出索引 (a CFTimeIndex
) 并使用其内置to_datetimeindex
方法:
datetimeindex = nor_xr.indexes['time'].to_datetimeindex()
然后,您可以将CFTimeIndex
其替换为DatetimeIndex
对应的:
nor_xr['time'] = datetimeindex
慕工程0101907
TA贡献1887条经验 获得超5个赞
我找到了一种从 cftime.DatetimeNoLeap 转换为 datetime 对象的简单方法。例如 datetimes 是一个 cftime.DatetimeNoLeap 对象的列表,其中 datetimes[0] = cftime.DatetimeNoLeap(1970, 1, 1, 12, 0, 0, 0, has_year_zero=True)
datetime.strptime(str(datetimes[0]),'%Y-%m-%d %H:%M:%S')
这将为您提供 datetime.datetime(1970, 1, 1, 12, 0)。
添加回答
举报
0/150
提交
取消