【发布时间】: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