Python 熊猫中的groupby元素如何基于连续的行值

Python 熊猫中的groupby元素如何基于连续的行值,python,pandas,pandas-groupby,Python,Pandas,Pandas Groupby,我有一个数据帧,如下所示: distance_along_path 0 0 1 2.2 2 4.5 3 7.0 4 0 5 3.0 6 5.0 7 0 8 2.0 9 5.0 10 7.0 我希望能够按照距离沿路径值对这些行进行分组,每次看到0时,都会创建一个新组,直到下一个0,所有这些行都在1组下,如下所示 distance_along_path

我有一个数据帧,如下所示:

   distance_along_path
0       0
1       2.2
2       4.5
3       7.0
4       0
5       3.0
6       5.0
7       0
8       2.0
9       5.0
10      7.0
我希望能够按照距离沿路径值对这些行进行分组,每次看到0时,都会创建一个新组,直到下一个0,所有这些行都在1组下,如下所示

   distance_along_path    group
0       0                  A
1       2.2                A
2       4.5                A    
3       7.0                A
4       0                  B
5       3.0                B
6       5.0                B
7       0                  C
8       2.0                C
9       5.0                C
10      7.0                C
谢谢

您可以尝试以下步骤:

说明

  • 用于查找等于
    0

  • 用于对
    True
    值应用累积计数

  • 代码+插图

    # Step 1 
    print(df.distance_along_path.eq(0))
    # 0      True
    # 1     False
    # 2     False
    # 3     False
    # 4      True
    # 5     False
    # 6     False
    # 7      True
    # 8     False
    # 9     False
    # 10    False
    # Name: distance_along_path, dtype: bool
    
    # Step 2
    print(df.assign(group=df.distance_along_path.eq(0).cumsum()))
    #     distance_along_path  group
    # 0                   0.0      1
    # 1                   2.2      1
    # 2                   4.5      1
    # 3                   7.0      1
    # 4                   0.0      2
    # 5                   3.0      2
    # 6                   5.0      2
    # 7                   0.0      3
    # 8                   2.0      3
    # 9                   5.0      3
    # 10                  7.0      3
    
    注意:正如您所看到的,组列是数字,而不是字母,但如果在
    groupby
    中使用,这并不重要

    # Step 1 
    print(df.distance_along_path.eq(0))
    # 0      True
    # 1     False
    # 2     False
    # 3     False
    # 4      True
    # 5     False
    # 6     False
    # 7      True
    # 8     False
    # 9     False
    # 10    False
    # Name: distance_along_path, dtype: bool
    
    # Step 2
    print(df.assign(group=df.distance_along_path.eq(0).cumsum()))
    #     distance_along_path  group
    # 0                   0.0      1
    # 1                   2.2      1
    # 2                   4.5      1
    # 3                   7.0      1
    # 4                   0.0      2
    # 5                   3.0      2
    # 6                   5.0      2
    # 7                   0.0      3
    # 8                   2.0      3
    # 9                   5.0      3
    # 10                  7.0      3