I have a pandas-dataframe that looks like:
INPUT - here the example runnable code to create the INPUT:
#Create Dataframe with example data
df_example = pd.DataFrame(columns=["START_D","ID_1", "ID_2", "STOP_D"])
df_example["START_D"] = ['2014-06-16', '2014-06-01', '2016-05-01','2014-05-28', '2014-05-20', '2015-09-01']
df_example['ID_1'] = [1,2,3,2,1,1]
df_example['ID_2'] = ['a', 'a', 'b', 'b', 'a', 'a']
df_example["STOP_D"] = ['2014-07-28', '2014-07-01', '2016-06-01', '2014-08-01', '2014-07-29', '2015-10-01']
#Convert to datetime
df_example["START_D"] = pd.to_datetime(df_example["START_D"])
df_example["STOP_D"] = pd.to_datetime(df_example["STOP_D"])
df_example
START_D ID_1 ID_2 STOP_D
0 2014-06-16 1 a 2014-07-28
1 2014-06-01 2 a 2014-07-01
2 2016-05-01 3 b 2016-06-01
3 2014-05-28 2 b 2014-08-01
4 2014-05-20 1 a 2014-07-29
5 2015-09-01 1 a 2015-10-01
and I am looking for a way to group by ID_1 and merge the rows where the START_D and STOP_D overlaps. The start_d will be the smallest and the stop_d the greatest. Below you can see the desired output that I get looping over all rows (iterrows) and checking one element at time.
OUTPUT Even if this approach works I think it is slow (for large DF) and I think there must be a more pythonic-pandas way to do that.
>>> df_result
START_D ID_1 STOP_D
0 2014-05-20 1 2014-07-29
1 2014-05-28 2 2014-08-01
2 2016-05-01 3 2016-06-01
3 2015-09-01 1 2015-10-01
thanks!