【问题标题】:How do I slice a pandas time series on dates not in the index?如何在索引中没有的日期对 pandas 时间序列进行切片?
【发布时间】:2016-01-18 22:52:12
【问题描述】:

我有一个由 datetime.date 索引的时间序列。这是该系列的第一个结:

1999-12-31  0
2000-06-30  170382.118454
2000-12-29  -319260.443362

我想从系列开始到 2000 年 12 月 28 日进行切片,但这不起作用,因为该日期不在索引中(当我尝试 original_series[:datetime.date(2000,12,28)] 时出现 KeyError。我也尝试过转换时间戳的索引,但这会给出非常虚假的结果(它会制造假结,见下文),所以我想知道是否有解决这个问题的好方法。

test = pd.Series(original_series.values, map(pd.Timestamp, original_series.index))

乍一看,这看起来不错:

1999-12-31         0.000000
2000-06-30    170382.118454
2000-12-29   -319260.443362

然后我尝试进行切片(2000 年 1 月的那些额外的日子是从哪里来的?):

In [84]: test[:'2000-12-28']
Out[84]: 
1999-12-31         0.000000
2000-06-30    170382.118454
2000-01-03    -71073.979016
2000-01-04    100498.744748
2000-01-05     91104.743684
2000-01-06     82290.255459

【问题讨论】:

    标签: python datetime pandas slice series


    【解决方案1】:

    如果ts 是你的time.serie,你可以这样做:

    In [77]: ts = pd.Series([99,65],index=pd.to_datetime(['2000-12-24','2000-12-30']))
    
    In [78]: ts
    Out[78]:
    2000-12-24    99
    2000-12-30    65
    dtype: int64
    
    In [79]: ts[ts.index<=pd.to_datetime('2000-12-28')]
    Out[79]:
    2000-12-24    99
    dtype: int64
    

    如果您将index 设置为string,请继续:

    ts[ts.index.map(pd.to_datetime)<=pd.to_datetime('2000-12-28')]
    

    【讨论】:

    • 您的回答绝对正确,但我也非常愚蠢——我没有按索引对时间序列进行排序,因此我对“制造”日期感到困惑。感谢您的帮助。
    【解决方案2】:

    有一种简单的方法可以做到这一点,而无需将其转换为时间序列对象。

    当您的索引不是日期时的场景:

    你的 df:
    索引   日期     数据
    0    2000-01-01 10
    1    2000-01-02 20
    2    2000-01-03 12

    首先,将您的日期转换为日期时间格式:

    df["date"] = pd.to_datetime(df["date"])
    

    迄今为止的第二次更改索引:

    df = df.set_index("date")
    

    您的 df 现在应该如下所示:

    日期       数据
    2000-01-01 10
    2000-01-02 20
    2000-01-03 12

    最后,您可以使用以下方法简单地操作行:

    df = df['2000-01-02':'2000-01-03']
    

    你的 df 现在看起来像这样:

    日期       数据
    2000-01-02 20
    2000-01-03 12

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 2020-04-09
      • 2012-12-15
      • 2012-09-17
      • 2018-11-19
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      相关资源
      最近更新 更多