Python dataframe:如何从DatetimeIndex获取期间对象的列(日历和会计年度和月份)?
我有一个数据框,这是前5个索引,有几行数据点不同,然后它会转到第二天Python dataframe:如何从DatetimeIndex获取期间对象的列(日历和会计年度和月份)?,python,pandas,dataframe,period,datetimeindex,Python,Pandas,Dataframe,Period,Datetimeindex,我有一个数据框,这是前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
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]
我希望添加一个包含日历年月份的列,以及两个包含不同会计年度和月份的列。
最好在不同的列中分隔年和月,例如:日历年、日历月、会计年、会计月。目标是在对其他列执行重新分组或重新采样时保留这些列值
我每个月都达到了赛昂以上的成绩
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)
然后将列表转换为系列或df,并将其添加回df
但我认为这是没有效率的(15万行数据),所以没有继续下去,以防你还没有找到解决方案 您可以执行以下操作:
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')绝对是一种有趣的方式。