Saturday, 24 November 2018

Datetime manipulation with lists

This is hard to explain but I will try to represent this in a small example:

NDD = 11/1/2018

number of payments:

1 0 2 0 2 1 1 0 2 1 1 1

Since the first month starts with 11 in NDD then the first element of my list will be 11, to compute the next element I take the first month (11) and subtract the first payment 1 and then the second element is 10. This proceeds and the pattern is clear if you follow the logic so I will have

11 10 10 8 8 6 5 4 4 2 1 12

To make it even more clear:

number_of_payments = [1 0 2 0 2 1 1 0 2 1 1 1]

Algorithm:

Step 1 - Create an empty list:

dates = []

Step 2 - Append the first month of NDD to the first index of dates

dates.append(NDD.month)

Step 3 - Now perform this formula:

for i in range(1,12):
dates[i] = (dates[i-1] + 12 - number_of_payments[i-1]) % 12

Step 4 - The final result will be

dates = [11 10 10 8 8 6 5 4 4 2 1 12]

Although I was able to do this I need to factor in the years of what NDD started with so what I want to have is

11/18 10/18 10/18 8/18 8/18 6/18 5/18 4/18 4/18 2/18 1/18 12/17

Now to go with what I have. This is what I have for NDD:

print(type(NDD))

Here is a view values from NDD

print(NDD[0:3])
0   2018-08-01
1   2018-07-01
2   2018-11-01

Here are the number_of_payments information:

print(type(number_of_payments))
<class 'list'>

Here is the first row (same as the example above)

print(number_of_payments[0])
[ 0.  1.  0.  1.  1.  1.  0.  5.  1.  0.  2.  1.]

This is what I am trying to do to get the result but it does not work:

dates = []
for i in range(len(number_of_payments)):
    dates.append([NDD[i]])
    for j in range(1, len(number_of_payments[i])):
        dates[i].append((dates[i][j-1] + 12 - number_of_payments[i][j-1]) % 12)
for date_row in dates:
    for n, i in enumerate(date_row):
        if i == 0:
            date_row[n] = 12
print(dates[0])

I get this error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-123-907a0962fd65> in <module>()
      4     dates.append([NDD[i]])
      5     for j in range(1, len(number_of_payments[i])):
----> 6         dates[i].append((dates[i][j-1] + 12 - number_of_payments[i][j-1]) % 12)
      7 for date_row in dates:
      8     for n, i in enumerate(date_row):

pandas/_libs/tslib.pyx in pandas._libs.tslib._Timestamp.__add__ (pandas\_libs\tslib.c:22331)()

ValueError: Cannot add integral value to Timestamp without freq.

I hope this is clear.



from Datetime manipulation with lists

No comments:

Post a Comment