pandas how to find continuous values in a series whose differences are within a certain distance

后端 未结 2 727
独厮守ぢ
独厮守ぢ 2021-02-15 02:44

I have a pandas Series that is composed of ints

a = np.array([1,2,3,5,7,10,13,16,20])
pd.Series(a)

0  1
1  2
2  3
3  5
4          


        
2条回答
  •  没有蜡笔的小新
    2021-02-15 03:17

    This is the pandas way, using groupby.

    n = 1
    
    s
    
    0     1
    1     2
    2     3
    3     5
    4     7
    5    10
    6    13
    7    16
    8    20
    dtype: int64
    
    m = ~s.diff().fillna(0).le(n)   
    v = s.groupby(m.cumsum()).apply(lambda x: x.tolist()).tolist()
    
    v
    [[1, 2, 3], [5], [7], [10], [13], [16], [20]]
    

提交回复
热议问题