大熊猫定义了6月1日至7月30日的季节性年份,而不是1月1日至12月31日

时间:2017-04-15 05:57:18

标签: python pandas

我有季节性雪数据,我希望按雪年(1954年7月1日 - 1955年6月30日)分组,而不是将一个冬季的数据分成两年(1954年1月1日 - 1954年12月31日和1月1日) ,1955年 - 1955年12月31日。)

example data

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

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

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

有没有比我更好的方法呢?

2 个答案:

答案 0 :(得分:3)

我认为是的,numpy.where

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

答案 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