3

I have two datetime arrays, and I am trying to output an array with only those dates which are repeated between both arrays.. I feel like this is something I should be able to answer myself, but I have spent a lot of time searching and I do not understand how to solve this.

>>> datetime1[0:4]
array([datetime.datetime(2014, 6, 19, 4, 0), 
datetime.datetime(2014, 6, 19, 5, 0),
datetime.datetime(2014, 6, 19, 6, 0),
datetime.datetime(2014, 6, 19, 7, 0)], dtype=object)

>>> datetime2[0:4]
array([datetime.datetime(2014, 6, 19, 3, 0),
datetime.datetime(2014, 6, 19, 4, 0),
datetime.datetime(2014, 6, 19, 5, 0),
datetime.datetime(2014, 6, 19, 6, 0)], dtype=object)

I've tried this below but I still do not understand why this does not work

>>> np.where(datetime1==datetime2)
(array([], dtype=int64),)

2 Answers 2

2

This:

datetime1==datetime2

Is an element-wise comparison. It compares [0] with [0], then [1] with [1], and gives you a boolean array.

Instead, try:

np.in1d(datetime1, datetime2)

This gives you a boolean array the same size as datetime1, set to True for those elements which exist in datetime2.

If your goal is only to get the values rather than the indexes, use this:

np.intersect1d(datetime1, datetime2)

https://docs.scipy.org/doc/numpy/reference/generated/numpy.intersect1d.html

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

Comments

2

I would say just iterate over the values of datetime1 and datetime2 and check for containment. So for example:

for date in datetime1:
    if date in datetime2:
        print(date)

1 Comment

For loops in NumPy are usually a poor solution.

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.