2

I am trying to combine dates1 and dates2 that combines the data frames sorts them in synchronous order. There are alike date values on both sets and the code should be able to only have one unique value in the output. what code will I need to get the Expected Output below?

import pandas as pd 
import numpy as np 

dates1 = pd.to_datetime(['2015-10-08 13:41:00', 
                 '2015-10-08 13:44:00', '2015-10-08 13:48:00',
                 '2015-10-08 13:49:00'])

dates2 = pd.to_datetime(['2015-10-08 13:42:00','2015-10-08 13:44:00', '2015-10-08 13:45:00', '2015-10-08 13:50:00'])

Expected output:

['2015-10-08 13:41:00',
 '2015-10-08 13:42:00', '2015-10-08 13:43:00',
 '2015-10-08 13:44:00', '2015-10-08 13:45:00',
 '2015-10-08 13:46:00', '2015-10-08 13:47:00',
 '2015-10-08 13:48:00', '2015-10-08 13:49:00',
 '2015-10-08 13:50:00', '2015-10-08 13:51:00']
1
  • where did 2015-10-08 13:43:00, 2015-10-08 13:46:00, 2015-10-08 13:47:00, 2015-10-08 13:51:00 come from? Commented Oct 30, 2021 at 6:19

2 Answers 2

2

Since they're both pandas.DatetimeIndex, you can use set operations from pandas.Index

dates1.union(dates2)
      

For multiple DatetimeIndex there are several options

dates1.union(dates2).union(dates3).union(dates4)

or a better approach

import functools
functools.reduce(pd.Index.union, [dates1, dates2, dates3, dates4])

or use the concat approach suggested by the other answer to this question

Sign up to request clarification or add additional context in comments.

2 Comments

thank you that works if I had dates3, dates4 .... etc could I unify multiple dates groups as a whole
I'll update the answer
1
pd.concat([date1,date2]).drop_duplicates().sort_values()

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.