Created
February 9, 2022 09:27
-
-
Save nchaly/22a213e53b5e4b8c0c50677af124cd13 to your computer and use it in GitHub Desktop.
Find pandas date range overlap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import pandas as pd | |
| import numpy as np | |
| days = pd.date_range('2021-01-01', '2021-12-31', freq='d') | |
| # items | |
| items = [] | |
| item_ids = range(100) | |
| for i in range(99): | |
| item = np.sort(np.random.choice(days, 2, replace=False)) | |
| items.append((item[0], item[1])) | |
| items.append((np.min(days), np.max(days))) | |
| # make interval index | |
| idx = pd.IntervalIndex.from_tuples(items, 'both') | |
| # check overlap with itself | |
| xx = pd.Series(idx).apply(lambda x: idx.overlaps(x)).values | |
| # debug dates overlap later | |
| dates_overlap = pd.DataFrame(np.vstack(xx), index=idx, columns=idx) | |
| # square matrix with item ids | |
| items_overlap = pd.DataFrame(dates_overlap.values, index=item_ids, columns=item_ids) | |
| # number of total overlaps per item: | |
| print(items_overlap.sum() - 1) | |
| # number of overlaps per item | |
| items_overlap.sum()-1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment