2017-10-13 127 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(或更多)事件(即使用第一事件的开始,最后端和求和值1和值2中的值)。

在上述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