【问题标题】:DateTimeIndex should be sorted, but isn'tDateTimeIndex 应该排序,但不是
【发布时间】:2020-12-08 23:36:39
【问题描述】:

我正在尝试对 pandas 中的 DateTime 系列进行重新采样,如下所示:

df = pd.read_csv(pathToParam + "/" + file)
df.drop(["LAT", "LON", "STATION_HEIGHT"], axis = 1, inplace=True)
df.set_index(df.DATE, inplace=True, drop=True)
if granularity == "daily":
     df.index = pd.to_datetime(df.index, cache=False)
     df = df.sort_index()
     df = df.resample("8H", closed="right").bfill()

Dataframe 如下所示:

DATE STATION_ID CLOUD_COVER_TOTAL
2016-01-01 1048 6.7
2016-01-02 1048 7.8
2016-01-03 1048 7.8

但我总是得到这个错误:

ValueError: index must be monotonic increasing or decreasing

我尝试了parse_dates = True 并在各种平台上搜索了可能的解决方案,但仍然一无所获。请帮忙。

【问题讨论】:

  • 一些想法 - 你使用最后一个熊猫版本吗?某些日期时间是否可能重复?
  • @jezrael - pandas 是 1.1.4,不能有任何重复
  • 如果测试删除closed="right"仍然错误?
  • 是的,还是一样
  • 无法模拟,我工作得很好。

标签: python pandas dataframe


【解决方案1】:

您的 csv 中的一行很可能有一个空值,日期应该是。

只有当我故意在其中输入空白日期时,我才能重现您的问题:

dateSeries = ["2016-01-01", "", "2016-01-02", "2016-01-04"]
data = [[1048, 6.7], [1048, 7.8], [1048, 7.8], [1048,7.8]]
df = pd.DataFrame(data, index = dateSeries, columns=["STATION_ID", "CLOUD_COVER_TOTAL"])
df.index = pd.to_datetime(df.index, cache=False)
df = df.sort_index()
df = df.resample("8H", closed="right").bfill()

画出这个错误

ValueError: index must be monotonic increasing or decreasing

如果我在每个索引中都有值,它就可以正常工作。您可以通过以下方式找到此类有问题的记录:

df.loc[None]

df.loc[""]

df.loc[pd.NaT]

【讨论】:

  • 我实际上有一个空白日期(神秘意外),谢谢您的时间先生!
猜你喜欢
  • 1970-01-01
  • 2011-06-30
  • 2014-03-12
  • 2021-05-06
  • 1970-01-01
  • 1970-01-01
  • 2011-11-27
  • 1970-01-01
  • 2011-05-29
相关资源
最近更新 更多