2015-04-02 49 views
1

我目前通過一次使用熊貓TimeGrouper:邊界爲分組

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

這給了我每年組分組我的數據。不過,我希望這些小組從3月份開始,每年確切地說是xxxx-03-01

執行此操作的一種方法是確保我的第一個數據點位於A March的第一個數據點,或者我的上一個數據點在2月28日結束並使用closed='right'。目前這些對我來說都不可行。從3月到3月,我還可以每年組織一次嗎?

+0

也許一個PeriodRange和一些切片呢? http://pandas.pydata.org/pandas-docs/dev/timeseries.html#periodindex-and-period-range – cphlewis 2015-04-02 17:53:34

回答

0

通過@cphlewis啓發,這裏是我的GroupBy方法每年的羣體,但在給定的一個月開始:

rng = pd.date_range('1/1/2011', periods=25, freq='M') 
ts = pd.DataFrame(np.random.randn(len(rng)), index=rng, columns=['ts']) 

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

    if starts[0] > ts.index[0]: 
     ts.loc[ts.index < starts[0], 'group'] = starts[0].year - 1 
    for start in starts: 
     end = '%d-%d'%(start.year+1, start.month-1) 
     ts.loc[start:end, 'group'] = start.year 
    return ts.groupby('group') 

groupBy = groupByYearMonth(ts, 3) 
print groupBy.mean(), groupBy.size() 
      ts 
group   
2010 0.638609 
2011 -0.124718 
2012 0.385539 group 
2010  2 
2011  12 
2012  11 
dtype: int64 
1

不雅,但我不認爲這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 
+0

我也找不到其他任何東西,所以我根據你的方法建立了我的最終方法。 – FooBar 2015-04-07 13:43:09