2017-04-15 109 views
3

我有我的雪今年要组季节性积雪的数据(1954年7月1日 - 1955年6月30日),而不是一个冬天的超过两年的数据分割(1954年1月1日 - 1954年12月31日和1955年1月1日 - 12月31日,1955年)熊猫从6月1日定义一个季节年12月31日

example data

我修改从这个问题的代码:

Using pandas to select specific seasons from a dataframe whose values are over a defined threshold(感谢垫)

def get_season(row): 
    if row['date'].month <= 7: 
     return row['date'].year 
    else: 
     return row['date'].year + 1 

df['Seasonal_Year'] = df.apply(get_season, axis=1) 

results of method call

有没有比我做得更好的方法?

回答

3

我想是的,有numpy.where

years = df['date'].dt.year 
df['Seasonal_Year'] = np.where(df['date'].dt.month <= 7, years, years + 1) 
3

可以使用pd.offsets.MonthBegin

考虑日期的数据帧df

df = pd.DataFrame(dict(Date=pd.date_range('2010-01-30', periods=24, freq='M'))) 

我们可以抵消日期和抢年

df.assign(Season=(df.Date - pd.offsets.MonthBegin(7)).dt.year + 1) 

     Date Season 
0 2010-01-31 2010 
1 2010-02-28 2010 
2 2010-03-31 2010 
3 2010-04-30 2010 
4 2010-05-31 2010 
5 2010-06-30 2010 
6 2010-07-31 2011 
7 2010-08-31 2011 
8 2010-09-30 2011 
9 2010-10-31 2011 
10 2010-11-30 2011 
11 2010-12-31 2011 
12 2011-01-31 2011 
13 2011-02-28 2011 
14 2011-03-31 2011 
15 2011-04-30 2011 
16 2011-05-31 2011 
17 2011-06-30 2011 
18 2011-07-31 2012 
19 2011-08-31 2012 
20 2011-09-30 2012 
21 2011-10-31 2012 
22 2011-11-30 2012 
23 2011-12-31 2012 
相关问题