我有一个熊猫数据框,大小为365,1 数据基于月份。 当前索引是0 1 2 ... 我想将当前索引转换为Year Month格式,其中第一个月是1987年1月。 因此索引0应该在1978年1月之前替换,索引1在1987年2月之前替换,等等。
我累了
pd.to_datetime(df, unit='m', origin=pd.Timestamp('1987-01-01'))
但是我一定做错了,因为它给了我错误
unit='m' not valid with non-numerical val='[8940982.93]'
答案 0 :(得分:1)
您可以使用DateOffset
s=df.index.map(lambda x : pd.DateOffset(months=x) + pd.to_datetime('1978-01-01'))
s.strftime('%Y-%B')
Index(['1978-January', '1978-February', '1978-March', '1978-April', '1978-May',
'1978-June', '1978-July', '1978-August', '1978-September',
'1978-October'],
dtype='object')