我在DataFrame中有一列带有值:
[1, 1, -1, 1, -1, -1]
如何将它们这样分组?
[1,1] [-1] [1] [-1, -1]
你可以groupby通过自定义使用Series:
Series
df = pd.DataFrame({'a': [1, 1, -1, 1, -1, -1]}) print (df) a 0 1 1 1 2 -1 3 1 4 -1 5 -1 print ((df.a != df.a.shift()).cumsum()) 0 1 1 1 2 2 3 3 4 4 5 4 Name: a, dtype: int32
for i, g in df.groupby([(df.a != df.a.shift()).cumsum()]): print (i) print (g) print (g.a.tolist()) a 0 1 1 1 [1, 1] 2 a 2 -1 [-1] 3 a 3 1 [1] 4 a 4 -1 5 -1 [-1, -1]