在 Pandas 中确定年度营业年度

Determining annual business year in Pandas

我有一个包含月份和年份的 DataFrame:

df:
    month   year
0   Jan     2012.0
1   Feb     2012.0
2   Mar     2012.0
3   Apr     2012.0
4   May     2012.0
5   Jun     2012.0
6   Jul     2012.0
7   Aug     2012.0
8   Sep     2012.0
9   Oct     2012.0
10  Nov     2012.0
11  Dec     2012.0

我想添加另一列来确定从每年 3 月开始的营业年度 类似这样的事情:。

df:
        month   year     business_year
    0   Jan     2012.0     2011
    1   Feb     2012.0     2011
    2   Mar     2012.0     2012
    3   Apr     2012.0     2012
    4   May     2012.0     2012
    5   Jun     2012.0     2012
    6   Jul     2012.0     2012
    7   Aug     2012.0     2012
    8   Sep     2012.0     2012
    9   Oct     2012.0     2012
    10  Nov     2012.0     2012
    11  Dec     2012.0     2012
    12  Jan     2013.0     2012
    13  Feb     2013.0     2012

IIUC,用pd.to_datetime转换为datetime。然后,您可以从每个日期减去 2 个月和 return 结果的相应年份。

import calendar

mapping = {calendar.month_abbr[i]: i for i in range(13)}
df['month'] = df['month'].map(mapping)

(pd.to_datetime(df.assign(day=1)) - pd.offsets.MonthBegin(2)).dt.year

0     2011
1     2011
2     2012
3     2012
4     2012
5     2012
6     2012
7     2012
8     2012
9     2012
10    2012
11    2012
dtype: int64

假设您的月份是一个字符串,您可以使用以下代码段:

df['business_year'] = df['year'] + df['month'].apply(lambda x: -1 if x in ('Jan', 'Feb') else 0)

或者,如果您想要更高性能的东西:

df['business_year'] = df['year'] + ~df1['month'].isin(('Jan', 'Feb')) - 1