如何在python中修改函数以包含额外的IntervalIndex

How do I modify function to include additional IntervalIndex in python

提问人:Tarak Pandya 提问时间:11/4/2023 更新时间:11/4/2023 访问量:34

问:

对于下面的代码,我正在尝试再添加一个 IntervalIndex(称为“values_1”)。有什么方法可以修改此函数,使其显示与这些 interval1 的重叠,并且 interval2 与该“values_1”重叠。请参考这篇文章。 提前非常感谢您!

    from itertools import combinations


def find_overlaps(g):
    idx = pd.IntervalIndex.from_arrays(
        g["Start DateTime"], g["End DateTime"], closed="both"
    )

    to_keep = set()
    for (i1, interval1), (i2, interval2) in combinations(zip(g.index, idx.values), 2):
        if interval1.overlaps(interval2):
            to_keep.add(i1)
            to_keep.add(i2)

    return g.loc[list(to_keep)]


df["Start DateTime"] = pd.to_datetime(df["Start DateTime"])
df["End DateTime"] = pd.to_datetime(df["End DateTime"])

out = df.groupby("values_1", group_keys=False).apply(find_overlaps)
print(out)
pandas 组合 python-itertools

评论


答: 暂无答案