首页 > 解决方案 > 对 DateTimeIndex 进行排序时 Pandas FutureWarning 的解决方法

问题描述

如此处所述,Pandas.sort_index() 在对 DateTimeIndex 进行排序时有时会发出 FutureWarning。该问题不可操作,因为它不包含 MCVE。这是一个:

import pandas as pd
idx = pd.DatetimeIndex(['2017-07-05 07:00:00', '2018-07-05 07:15:00','2017-07-05 07:30:00'])
df = pd.DataFrame({'C1':['a','b','c']},index=idx)
df = df.tz_localize('UTC')
df.sort_index()

警告看起来像:

FutureWarning:使用 'datetime64[ns]' dtype 将时区感知 DatetimeArray 转换为时区朴素 ndarray

堆栈(Pandas 0.24.1)是:

__array__, datetimes.py:358
asanyarray, numeric.py:544
nargsort, sorting.py:257
sort_index, frame.py:4795

该错误是从 datetimes.py 发出的,要求使用 dtype 参数调用它。但是,没有办法通过 nargsort 一直强制执行该操作——看起来遵守 datetimes.py 的请求需要同时更改 pandas 和 numpy。

在这里报道。同时,您能想出一个我错过的解决方法吗?

标签: pandas

解决方案


已确认 0.24.2 里程碑的问题。解决方法是过滤警告,因此:

with warnings.catch_warnings():
    # Pandas 0.24.1 emits useless warning when sorting tz-aware index
    warnings.simplefilter("ignore")
    ds = df.sort_index()

推荐阅读