3

I have a Pandas dataframe with the following datetime index:

DatetimeIndex(['2020-01-02', '2020-01-03', '2020-01-06', '2020-01-07',
               '2020-01-08', '2020-01-09', '2020-01-10', '2020-01-13',
               '2020-01-14', '2020-01-15',
               ...
               '2020-01-17', '2020-01-21', '2020-01-22', '2020-01-23',
               '2020-01-24', '2020-01-27', '2020-01-28', '2020-01-29',
               '2020-01-30', '2020-01-31'],
              dtype='datetime64[ns]', name='Date', length=49098, freq=None)

I want to get the rows which intersect with the following datetime index:

DatetimeIndex(['2020-01-02', '2020-01-03', '2020-01-06', '2020-01-07',
               '2020-01-08', '2020-01-09', '2020-01-10'],
              dtype='datetime64[ns]', name='Date', freq=None)

What is the most natural (aka "Pythonic") way to do it?

1 Answer 1

5

Use Index.intersection:

idx = idx1.intersection(idx2)

Or, if the indexes have not been previously defined:

idx = df1.index.intersection(df2.index)
Sign up to request clarification or add additional context in comments.

4 Comments

At your service.
This is how you get the intersection of two DateTimeIndex as a DateTimeIndex. But how do you get the rows from the original dataframe (which was the original question)? df.loc[idx] gives me a dataframe that has more rows than the original df. My original df has multiple occurances of the same dates.
@jezrael I knew you are fast, but I did not know you were this fast! Yes, it works.
thanks @jezrael ! i was searching almost hour looking for clean answer

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.