2017-10-13 4 views
1

こんにちはに基づいてデータフレームパンダの行をマージするデータフレームのイベント(行)のセットを含むdfは条件

を持っています。

df = pd.DataFrame(data=[[1, 2, 7, 10], 
        [10, 22, 1, 30], 
        [30, 42, 2, 10], 
        [100,142, 22,1], 
        [143, 152, 2, 10], 
        [160, 162, 12, 11]],columns=['Start','End','Value1','Value2']) 

df 
Out[15]: 
    Start End Value1 Value2 
0  1 2  7  10 
1  10 22  1  30 
2  30 42  2  10 
3 100 142  22  1 
4 143 152  2  10 
5 160 162  12  11 

2(またはそれ以上)の連続したイベントが< = 10の場合は遠く離れて私は、2(またはそれ以上)のイベントをマージしたい(つまり最初のイベント、最後の最後の開始を使用し、合計Value1とValue2の値)。 DF上記の例では

次のようになります。

完全に可能です
df 
Out[15]: 
    Start End Value1 Value2 
0  1 42  10  50 
1 100 162  36  22 

答えて

3

df.groupby(((df.Start - df.End.shift(1)) > 10).cumsum()).agg({'Start':min, 'End':max, 'Value1':sum, 'Value2': sum}) 

説明:

start_end_differences = df.Start - df.End.shift(1) #shift moves the series down 
threshold_selector = start_end_differences > 10 # will give you a boolean array where true indicates a point where the difference more than 10. 
groups = threshold_selector.cumsum() # sums up the trues (1) and will create an integer series starting from 0 
df.groupby(groups).agg({'Start':min}) # the aggregation is self explaining 

ここではとらわれないまま一般化ソリューションです。その他の列:

cols = df.columns.difference(['Start', 'End']) 
grps = df.Start.sub(df.End.shift()).gt(10).cumsum() 
gpby = df.groupby(grps) 
gpby.agg(dict(Start='min', End='max')).join(gpby[cols].sum()) 

    Start End Value1 Value2 
0  1 42  10  50 
1 100 162  36  22 
+0

ニースの答え。一を足す。 – piRSquared

+1

私はあなたの答えを編集しました。あなたが好きではない場合は、気をつけてください。 – piRSquared