首页 > 解决方案 > 数据框:如何从 DatetimeIndex 获取 Period 对象列(日历+会计年度和月份)?

问题描述

我有一个数据框,这些是前 5 个索引,有几行具有不同数据点的日期,然后转到第二天

DatetimeIndex(['2014-01-01', '2014-01-01', '2014-01-01', '2014-01-01',
               '2014-01-01'],
              dtype='datetime64[ns]', name='DayStartedOn', freq=None)

这是当前列 dtypes

country                  object
type                     object
name                     object
injection               float64
withdrawal              float64
cy_month              period[M]

我希望添加一个带有日历年月的列,以及 2 个具有不同会计年度和月份的列。最好在不同的列中分隔年和月,例如:日历年、日历月、会计年度、会计月。目标是在我对其他列执行重新组合或重新采样时保留这些列值

我达到了 cy_month 以上

df['cy_month']=df.index.to_period('M')

即使我对此感到不舒服,因为我想要的是月经,而不是月末

我尝试为日历年添加这两列:

pd.Period(df_storage_clean.index.year, freq='A-DEC')  

另一个财政年度:

pd.Period(df_storage_clean.index.year, freq='A-SEP') 

但有追溯:

ValueError: Value must be Period, string, integer, or datetime

所以我开始不逐行循环使用熊猫并添加到列表中,

lst_period_cy=[]
for y in lst_cy:
    period_cy=pd.Period(y, freq='A-DEC')
    lst_period_cy.append(period_cy)

然后将列表转换为 Series 或 df 并将其添加回 df

但我认为它效率不高(150k 行数据)所以没有继续

标签: pythonpandasdataframeperioddatetimeindex

解决方案


以防万一您还没有找到解决方案...

您可以执行以下操作:

df.reset_index(drop=False, inplace=True)
df['cal_year_month'] = df.DayStartedOn.dt.month
df['cal_year'] = df.DayStartedOn.dt.year
df['fisc_year'] = df.DayStartedOn.apply(pd.Period, freq='A-SEP')
df.set_index('DayStartedOn', drop=True, inplace=True)

我的假设是,与您的示例一样,索引名为DayStartedOn. 如果不是这种情况,则必须相应地调整代码。


推荐阅读