Skip to content
Advertisement

List ‘none’ data type element replacing using another element with time info

I have a list of dates to be used in a time series. And the list looks like as follow:

JavaScript

I want to fill up the missing dates with what they were actually supposed to be. For example, here in the list x, x[2] = '2019-07-01' that represents the month of July, and the previous two elements are type None, the previous two elements will be replaced by ‘2019-06-01’ and '2019-05-01' respectively. The same concept will be followed for later elements. Finally, the updated list will as follow:

JavaScript

Advertisement

Answer

The basic idea is you take the first month + associated index in the list and compare all other index positions relative to that “fixed” month.

Using the function relativedelta() from Python’s dateutil package, the current index in the list, and the index of the fixed month, you can add or subtract from the fixed month to get the appropriate month for that slot in the list.

Unlike the other answer, this does not make assumptions on how many “empty slots” there are before the first month in the list.

JavaScript

Outputs

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement