【问题标题】:dataframe: how to get columns of Period objects (calendar+fiscal year and month)from DatetimeIndex?数据框:如何从 DatetimeIndex 获取 Period 对象列(日历+会计年度和月份)?
【发布时间】:2020-11-30 20:56:57
【问题描述】:

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

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

这是当前列的数据类型

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') 

但有 Traceback:

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

所以我开始不逐行使用 pandas 并添加到列表中,

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 行数据)所以没有继续

【问题讨论】:

    标签: python pandas dataframe period datetimeindex


    【解决方案1】:

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

    您可以执行以下操作:

    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。如果不是这种情况,则必须相应地调整代码。

    【讨论】:

    • 非常感谢,df['fisc_year'] = df.DayStartedOn.apply(pd.Period, freq='A-SEP') 绝对是一种有趣的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2012-02-16
    • 2021-11-03
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    相关资源
    最近更新 更多