python - Pandas 时间分组 : Boundaries for the grouping

标签 python datetime pandas

我目前正在使用按时间对数据进行分组

df.groupby(pd.TimeGrouper('AS'))

这给了我年度团体。不过,我希望这些小组从三月份开始,确切地说是每年 xxxx-03-01

强制执行此操作的一种方法是确保我的第一个数据点首先在 A 月,或者我的最后一个数据点在 2 月 28 日结束并使用 close='right'。目前这些对我来说都不可行。我还能如何每年从三月到三月分组?

最佳答案

不优雅,但我没有看到 groupby 内置了这样的参数:

import pandas as pd
from numpy.random import randn

rng = pd.date_range('1/1/2011', periods=25, freq='M')
ts = pd.Series(randn(len(rng)), index=rng)

def truncYears(ts, month):
    starts = ts[ts.index.month==month].index  # Fix if multiple entries per month.

    groups = {}
    if starts[0] > ts.index[0]:
        groups[ts.index[0]] = ts[ts.index < starts[0]]
    for start in starts:
        end = '%d-%d'%(start.year+1, start.month-1)
        print(start, end)
        groups[start] = ts[start:end]

    return groups

groups = truncYears(ts, 3)
for k in groups:
    print(groups[k])

结果(注意字典键未排序,因此年份不按顺序排列):

2011-01-31   -1.719806
2011-02-28   -0.657064
Freq: M, dtype: float64
2012-03-31    1.200984
2012-04-30   -0.496715
2012-05-31   -0.998218
2012-06-30    1.711504
2012-07-31    0.304211
2012-08-31    1.091810
2012-09-30   -0.716785
2012-10-31   -0.996493
2012-11-30   -0.541812
2012-12-31    1.027787
2013-01-31    0.249775
Freq: M, dtype: float64
2011-03-31   -1.406736
2011-04-30    0.245077
2011-05-31   -0.010090
2011-06-30   -1.459824
2011-07-31    0.150871
2011-08-31   -1.223533
2011-09-30    0.859539
2011-10-31    0.623674
2011-11-30   -2.071204
2011-12-31    0.254750
2012-01-31    0.667076
2012-02-29    0.076249
Freq: M, dtype: float64

关于python - Pandas 时间分组 : Boundaries for the grouping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29416238/

相关文章:

python - Django 引发 NoReverseMatch : 'en-us' is not a registered namespace

python - 将 CSV 数据读取为标题和值对

python - 需要将整个列从字符串格式转换为 Dataframe 的日期格式

python Pandas : split comma-separated column into new columns - one per value

python - 从 python 中的元组的元组中获取元素

python - 使用 Python 解析文件 (ics/Vcalendar)

Java 时间表达式求值

forms - zf2 表单验证器 DateTime dateInvalidDate

python - 转换 Pandas DataFrame,添加行值作为列标题

python - 如何用 None 替换字符串值 - python,pandas dataframe