pandas 如何分组熊猫数据帧中的连续值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40802800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:30:15  来源:igfitidea点击:

How to groupby consecutive values in pandas DataFrame

pythonpandasdataframegroup-bycumsum

提问by Bryan Fok

I have a column in a DataFrame with values:

我在 DataFrame 中有一个带有值的列:

[1, 1, -1, 1, -1, -1]

How can I group them like this?

我怎样才能像这样将它们分组?

[1,1] [-1] [1] [-1, -1]

回答by jezrael

You can use groupbyby custom Series:

您可以groupby通过自定义使用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]

回答by YOBEN_S

Using groupbyfrom itertoolsdata from Jez

使用groupbyitertools来自杰斯数据

from itertools import groupby
[ list(group) for key, group in groupby(df.a.values.tolist())]
Out[361]: [[1, 1], [-1], [1], [-1, -1]]