【问题标题】:Cannot do positional indexing on DatetimeIndex with these indexers无法使用这些索引器对 DatetimeIndex 进行位置索引
【发布时间】:2021-08-19 17:02:57
【问题描述】:

我有一个带有日期时间索引的时间序列数据框“his”,我想从中提取一定范围的时间步长。起点“selected_var_start”采用日期时间索引格式(从另一个数据帧中提取)。我想总共提取 24 小时。

我尝试这样做:his = his.iloc[selected_var_start:(selected_var_start+pd.DateOffset(hours=24))]

我收到以下错误TypeError: cannot do positional indexing on DatetimeIndex with these indexers [DatetimeIndex(['2010-11-12 19:00:00'], dtype='datetime64[ns]', name='Datetime', freq=None)] of type DatetimeIndex

我做错了什么?

【问题讨论】:

  • iloc 用于“纯粹基于整数位置的索引以按位置选择” - 请改用loc
  • 如果我使用 his = his.loc[selected_var_start:(selected_var_start+pd.DateOffset(hours=24))] 我会得到 "pandas.errors.InvalidIndexError: DatetimeIndex(['2010-11-12 19:00:00'], dtype='datetime64[ns]', name ='日期时间', freq=None)"
  • 这只是一般建议;如需详细解答,请提供minimal reproducible example

标签: python pandas datetime indexing


【解决方案1】:

loc 与字符串一起使用

pd.DataFrame(index=pd.date_range('11/01/2010', '12/01/2010')).loc['2010-11-12': '2010-11-13']

【讨论】:

  • 我能以某种方式包含时间吗?我想我必须使用 selected_var_start.strftime(dateformat) 但我看起来只能使用日期而不是白天的时间?
【解决方案2】:

您需要访问selected_var_start 的第一个元素。试试这个selected_var_start[0]。这会将您的元素从 DatetimeIndex 转换为简单的 Timestamp,它适用于 loc。

his.loc[selected_var_start[0]:(selected_var_start[0]+pd.DateOffset(hours=24))]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2020-10-06
    • 1970-01-01
    • 2020-09-13
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多