The above answer is inspiring but there is something need to be improved.
(1) It should be documented that shift()
will shift up one record, not down.
(2) It does not consider when a row is within the boundary of the previous record. Just add cummax()
and will solve.
Here is the modified code:
import pandas as pd
import io
## load data
raw ="""START,FINISH
0.000000 ,10.000000
2.000000 ,3.000000
10.000000 ,4500.182997
5000.00 ,7000.000000
6000 ,8500.687227
9850.123,9990.000000
"""
buf_bytes = io.StringIO(raw)
df=pd.read_csv(buf_bytes)
## solution
df.sort_values("START", inplace=True)
## This line compares if START of present row is greater than largest FINISH in previous
## rows ("shift" shifts up FINISH by one row). The value of expression before
## cumsum will be True if interval breaks (i.e. cannot be merged), so
## cumsum will increment group value when interval breaks (cum sum treats True=1, False=0)
df["group"]=(df["START"]>df["FINISH"].shift().cummax()).cumsum()
print(df)
## this returns min value of "START" column from a group and max value fro m "FINISH"
result=df.groupby("group").agg({"START":"min", "FINISH": "max"})
print(result)
output:
START FINISH
group
0 0.000 4500.182997
1 5000.000 8500.687227
2 9850.123 9990.000000
Results from the unmodified solution:
START FINISH
group
0 0.000 10.000000
1 10.000 4500.182997
2 5000.000 8500.687227
3 9850.123 9990.000000