熊猫重新采样开始日期

jsi*_*ell 20 python time-series dataframe pandas pandas-resample

我想使用特定日期(或月份)作为第一个 bin 的边缘对 Pandas 对象重新采样。例如,在下面的代码片段中,我希望我的第一个索引值是2020-02-29,我很乐意指定start=2or start="2020-02-29"

>>> dates = pd.date_range("2020-01-29", "2021-07-04")
>>> s = pd.Series(range(len(dates)), index=dates)
>>> s.resample('4M').count()
2020-01-31      3
2020-05-31    121
2020-09-30    122
2021-01-31    123
2021-05-31    120
2021-09-30     34
Freq: 4M, dtype: int64
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我能想到的最干净的用途,pd.cut并且groupby

>>> rule = "4M"
>>> start = pd.Timestamp("2020-02-29") - pd.tseries.frequencies.to_offset(rule)
>>> end = s.index.max() + pd.tseries.frequencies.to_offset(rule)
>>> bins = pd.date_range(start, end, freq=rule)
>>> gb = s.groupby(pd.cut(s.index, bins)).count()
>>> gb.index = gb.index.categories.right
>>> gb
2020-02-29     32
2020-06-30    122
2020-10-31    123
2021-02-28    120
2021-06-30    122
2021-10-31      4
dtype: int64
Run Code Online (Sandbox Code Playgroud)

Tom*_*Tom 8

我的回答感觉有点笨拙,但使用resample并提供了所需的输出。查找指定日期之前一个 bin 长度的日期(例如 4 个月,或特别是月末),将其附加到s,然后resample

rule = '4M'
date = '02-29-2020'

base_date = pd.to_datetime(date) - pd.tseries.frequencies.to_offset(rule)
s.loc[base_date] = np.nan
output = s.resample(rule=rule, label='right',).count()
output=output[output.index >= date]
Run Code Online (Sandbox Code Playgroud)

结果:

2020-02-29     32
2020-06-30    122
2020-10-31    123
2021-02-28    120
2021-06-30    122
2021-10-31      4
Freq: 4M, dtype: int64
Run Code Online (Sandbox Code Playgroud)

我添加了output=output[output.index >= date]b/c 否则你会得到一个额外的空箱:

2019-10-31      0
2020-02-29     32
2020-06-30    122
2020-10-31    123
2021-02-28    120
2021-06-30    122
2021-10-31      4
Freq: 4M, dtype: int64
Run Code Online (Sandbox Code Playgroud)

  • `output = output.loc[date:]` 或 `output[1:]` 也可以。 (2认同)

Moh*_*faa 7

您需要使用的所有内容pd.cut如下:

>>> gb = pd.cut(s.index, bins).value_counts()
>>> gb.index = gb.index.categories.right
>>> gb
2020-02-29     32
2020-06-30    122
2020-10-31    123
2021-02-28    120
2021-06-30    122
2021-10-31      4
dtype: int64
Run Code Online (Sandbox Code Playgroud)

没有必要使用 groupby

  • 我只是说你的答案可能会产生误导,因为看起来你用 2 行替换了 6 行,但你的答案也需要 6 行。您刚刚缩短了 6 行中的 1 行(这很好,而且速度更快)。我唯一的建议是更清楚地了解您的答案与OP中的答案有何不同以及如何改进。您还可以显示速度的增加。(我在我的“答案”中这样做了,但我使用的时间是你的改进和@ALollz的改进的组合。) (2认同)