简体   繁体   中英

Pandas convert a DataFrame [monthly data] with index 0 1 2 … to a specific date Year-month range

I have a panda DataFrame which is of size 365,1 Data is based by month. The current index is 0 1 2 ... I want to convert the current index to a Year Month format where the first month is 1987 January. So the index 0 should by replace by 1978 January , the index 1 by 1987 February etc.

I have tired

pd.to_datetime(df, unit='m', origin=pd.Timestamp('1987-01-01'))

But I must have done something wrong as it gives me the error

 unit='m' not valid with non-numerical val='[8940982.93]'

You can check with 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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM