Search code examples
pythonpandasdatetimeindex

Pandas: find the first couple of timestamp indices that are the same given two dataframes


I have the following df1:

                      Value
2020-06-02 00:00:00   17
2020-06-03 00:00:00   10
2020-06-05 00:00:00   86

and the following df2:

                      Value
2020-06-01 00:00:00   16
2020-06-04 00:00:00   9
2020-06-05 00:00:00   86

and I know that the two dataframes have different length. How can I find the day of the first and the last couple of indices where df1.index == df2.index?

In my example, the day of the first matching couple would be 2020-06-05 00:00:00.


Solution

  • Use Index.intersection and then use minimal and maximal values:

    idx = df1.index.intersection(df2.index)
    min1 = idx.min()
    max1 = idx.max()