python - 如何对 pandas DataFrame 中的连续值进行分组

标签 python pandas dataframe group-by cumsum

我在 DataFrame 中有一个列,其中包含值:

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

如何将它们分组?

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

最佳答案

您可以使用groupby按自定义系列:

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]

关于python - 如何对 pandas DataFrame 中的连续值进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40802800/

相关文章:

python - 使用一个大的 INSERT 语句保存许多 Django 对象

python - 如何最好地将包含列表或元组的 Pandas 列提取到多个列中

python - 如何重新采样并将值计数为新的列标题并计数为它的值

r - 使用 data.table 根据条件创建二进制列

python - 即使由于 dagbag 错误而从 UI 手动触发了 dags,Airflow 也不会触发 dags

python - 如何在多索引数据帧上同时执行两个切片?

python - 当 pandas 的日期发生变化时,如何减去时间?

python-3.x - Python 中的重采样

Python Pandas 数据框 ValueError : Trying to store a string with len

python - 抛出 ZeroDivisionError