Search code examples
pythonpandasdataframerecode

Recode continuous number into continuous dates in Python


I have a variable looks like

1,1,1,1, 2,2,2,3,3,3,3,3,4,4,5,6,6,6, ,.....100,100,100
I would like to recode them into dates
1=31.12.2020
2=30.12.2020
3=29.12.2020
...

In my real case, there will be more than 1000 dates (or more) to be recoded and also have to consider the leap year.

appreciate if there is an elegant way to deal with it by python pandas.

Thank you very much for helping a beginner.


Solution

  • Pandas has a "date_range" method that can return a sequence of regularly spaced date objects based on a start date, an ~'increment', and an end date. You could use this to build a sequence of dates spaced by single days, and then use that to associate each of those indexes (1,1,1,2,2,...) with a date object in the date_range sequence.

    pandas date_range docs