我有一个dataframe,这是前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]我希望添加一个具有日历年月的列,以及两个具有不同会计年度和月份的列。最好在不同的列中分隔年份和月份,如:日历年、日历月、会计年度、会计月份。目标是在我对其他列执行重新分组或重新采样时保留这些列值
我通过以下方式达到了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所以我开始不再使用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
但我认为它的效率不高(15万行数据),所以没有继续
发布于 2020-12-02 01:21:38
以防你还没有找到解决方案...
您可以执行以下操作:
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。如果不是这样,那么代码必须进行相应的调整。
https://stackoverflow.com/questions/65081079
复制相似问题