【发布时间】:2023-01-17 23:47:26
【问题描述】:
我有多个 Pandas 系列的 datetime64 值,我想使用任意 bin 大小将它们分组。
我找到了 Series.to_period() 函数,它完全符合我的要求,只是我需要更多地控制所选的 bin 大小。 to_period 允许我按整年、月、日等分类,但我也想按 5 年、6 小时或 15 分钟分类。使用像 5Y、6H 或 15min 这样的语法在 Pandas 的其他角落有效,但显然不在这里。
s = pd.Series(["2020-02-01", "2020-02-02", "2020-02-03", "2020-02-04"], dtype="datetime64[ns]")
# Output as expected
s.dt.to_period("M").value_counts()
2020-02 4
Freq: M, dtype: int64
# Output as expected
s.dt.to_period("W").value_counts()
2020-01-27/2020-02-02 2
2020-02-03/2020-02-09 2
Freq: W-SUN, dtype: int64
# Output as expected
s.dt.to_period("D").value_counts()
2020-02-01 1
2020-02-02 1
2020-02-03 1
2020-02-04 1
Freq: D, dtype: int64
# Output unexpected (and wrong?)
s.dt.to_period("2D").value_counts()
2020-02-01 1
2020-02-02 1
2020-02-03 1
2020-02-04 1
Freq: 2D, dtype: int64
【问题讨论】:
标签: python pandas datetime binning