【问题标题】:Pandas Specify time range in DatetimeIndexPandas 在 DatetimeIndex 中指定时间范围
【发布时间】:2016-09-04 16:29:29
【问题描述】:

我正在为不同的 pandas 索引格式而苦苦挣扎。

我的单变量时间序列(数据)看起来像这样

2015-01-01 22:00:01.973    1.210525
2015-01-01 22:00:03.297    1.210490
2015-01-01 22:00:23.922    1.210485
2015-01-01 22:00:24.507    1.210480
2015-01-01 22:01:05.979    1.210490
2015-01-01 22:01:08.390    1.210525
2015-01-01 22:01:09.899    1.210520
2015-01-01 22:01:09.950    1.210505
2015-01-01 22:01:13.576    1.210505
2015-01-01 22:01:19.984    1.210485
2015-01-01 22:01:27.936    1.210510

在哪里

>>> type(data)
<class 'pandas.core.series.Series'>
>>> type(data.index)
<class 'pandas.tseries.index.DatetimeIndex'>
>>> 

我有一个提取起点和终点的函数,比如说

>>>start
textdate
2015-01-01 22:00:03.297    1.210490
Name: mean, dtype: float64
>>>

>>>end
textdate
2015-01-01 22:01:19.984    1.210485
Name: mean, dtype: float64
>>>

如何根据索引值从头到尾对系列进行切片,这些索引值本身似乎是 DatetimeIndex 格式

>>> start.index
DatetimeIndex(['2015-01-01 22:00:03.297'], dtype='datetime64[ns]', name=u'textdate', freq=None)
>>> 

我试过了

series = data[start.index : end.index]

这给了我

TypeError: Cannot convert input to Timestamp 

但我未能将 DatetimeIndex 对象 start 和 end 转换为 Timestamps...

【问题讨论】:

  • data.loc[start.index : end.index] 工作吗?
  • data.loc[...] 出现同样的错误
  • 好的,data.loc[start.index[0] : end.index[0]] 怎么样?
  • 成功了!谢谢!

标签: python pandas indexing timestamp


【解决方案1】:

您需要访问单行 Series 内的标量值并将其传递给 loc 以切片 df:

data.loc[start.index[0] : end.index[0]]

【讨论】:

    【解决方案2】:

    我认为您在切片中使用了对 Series 的引用。而是尝试:

    series = data[start.index[0] : end.index[0]]
    

    我认为您的startend 是单周期系列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-02
      • 2020-01-30
      • 2021-05-16
      • 2018-08-18
      • 2018-04-13
      • 2017-11-09
      • 2018-04-30
      • 1970-01-01
      相关资源
      最近更新 更多