1

I have a fixed-length Time list:

time_list = ['21:00:00', '22:00:00', '23:00:00', '00:00:00', '01:00:00']

However, I have a long Date list:

date_list = 
['2019-07-09',
 '2019-07-09',
 '2019-07-09',
 '2019-07-09',
 '2019-07-09',
 '2019-07-09',
 '2019-07-09',
 '2019-07-10',
 '2019-07-10',
 '2019-07-10',
 '2019-07-10',
 '2019-07-08',
 '2019-07-08',
 '2019-07-08'
 ....
 ]

What I want to do is join date_list and time_list so the new df looks like this:

date_time =
['2019-07-09 21:00:00',
 '2019-07-09 22:00:00',
 '2019-07-09 23:00:00',
 '2019-07-09 00:00:00',
 '2019-07-09 01:00:00',
 '2019-07-09 21:00:00',
 '2019-07-09 22:00:00',
 '2019-07-10 23:00:00',
 '2019-07-10 00:00:00',
 '2019-07-10 01:00:00',
 '2019-07-10 21:00:00',
 '2019-07-08 22:00:00',
 '2019-07-08 23:00:00',
 '2019-07-08 00:00:00'
 ....
 ]

As you can see that the time_list is applied to date_list similar to one to one mapping. When the time_list runs out of value, it is repeated again but date_list is the same length and won't repeat.

What did I do?

I tried to do:

pd.MultiIndex.from_product([date_list, time_list]).map(' '.join).tolist()

But it does for each date_list joins time_list which gives extra values.

I also tried to do this but wont work:

[date_list  + " " + time_list]  

Can you please help?

2 Answers 2

1

Try with

n=1+len(date_list)//len(time_list)
[x + ' ' +y for x , y in zip(date_list,(time_list*n)[:len(date_list)])]

Or we using the itertools.cycle

import itertools
[x+' '+y for x,y in zip(date_list, itertools.cycle(time_list))]
Sign up to request clarification or add additional context in comments.

Comments

1

On a very intuitive level I would simply have 2 for loops and a 'cyclical numerator' such that:

from collections import Counter

date_dict = Counter(date_list)
date_time = []
cyclical = 0

for d in date_dict:
    index = 0
    n = date_dict[d]
    for _ in range(n): 
        t = time_list[cyclical%len(time_list)]  
        cycle += 1
        date_time.append(d+" "+t)

desired result:

['2019-07-09 21:00:00',
 '2019-07-09 22:00:00',
 '2019-07-09 23:00:00',
 '2019-07-09 00:00:00',
 '2019-07-09 01:00:00',
 '2019-07-09 21:00:00',
 '2019-07-09 22:00:00',
 '2019-07-10 23:00:00',
 '2019-07-10 00:00:00',
 '2019-07-10 01:00:00',
 '2019-07-10 21:00:00',
 '2019-07-08 22:00:00',
 '2019-07-08 23:00:00',
 '2019-07-08 00:00:00']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.