簡體   English   中英

如何根據連續行值對 pandas 中的元素進行分組

[英]How do groupby elements in pandas based on consecutive row values

我有一個 dataframe 如下:

   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

我希望能夠通過 distance_along_path 值對這些進行分組,每次看到 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

謝謝

您可以嘗試eq后跟cumcun

df["group"] = df.distance_along_path.eq(0).cumsum()

說明

  1. 使用eq查找等於0的值

  2. 使用cumcunTrue值應用累積計數

代碼+插圖

# 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

注意:如您所見, group 列是數字而不是字母,但如果在groupby中使用它並不重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM