一种方法是创建一些临时列
# First create a new series, which is true whenever the value changes from a zero value to a non-zero value (which will be at the start of each group) nonzero = (df['Value1'] > 0) & (df['Value1'].shift(1) == 0) # Take a cumulative sum. This means each group will have it's own number. df['group'] = df['nonzero'].cumsum() # Group by the group column gb = df[df['Value1'] > 0].groupby('group')
然后,您可以使用聚合函数获取此组的聚合 http://pandas.pydata.org/pandas-docs/stable/groupby.html
对于您特别希望获得的输出,请看一下这个答案: Python Pandas:同一列的多个聚合
df2 = gb.agg({ 'ActivityDateTime': ['first', 'last'], 'Value1': 'mean', 'Value2': 'mean'})