如何根据不在索引中的日期对 pandas 时间序列进行切片?

How do I slice a pandas time series on dates not in the index?

我有一个索引为 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

你可以简单地做,如果 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')]

有一种简单的方法可以做到这一点,无需将其转换为 time-series 对象。

索引不是日期的情况:

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

首先,将您的日期转换为 date-time 格式:

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