簡體   English   中英

當連續行的差異小於一個值時,對 pandas 數據幀中的行進行分組

[英]group rows in a pandas data frame when the difference of consecutive rows are less than a value

我有一個這樣的數據框,

col1    col2    col3
 1        2       3
 2        3       4
 4        2       3
 7        2       8
 8        3       4
 9        3       3
 15       1       12

現在我想對兩個連續 col1 行之間差異小於 3 的行進行分組。並對其他列值求和,用組的最后一個值創建另一列(col4),所以最終的數據框看起來像,

col1    col2    col3    col4
  1       7       10     4
  7       8       15     9

使用 for 循環來做到這一點很乏味,尋找一些 pandas 快捷方式來最有效地做到這一點。

您可以對 groupby 進行命名聚合:

(df.groupby(df.col1.diff().ge(3).cumsum(), as_index=False)
   .agg(col1=('col1','first'),
        col2=('col2','sum'),
        col3=('col3','sum'),
        col4=('col1','last'))
)

Output:

   col1  col2  col3  col4
0     1     7    10     4
1     7     8    15     9
2    15     1    12    15

在沒有命名聚合的情況下進行更新,您可以執行以下操作:

groups = df.groupby(df.col1.diff().ge(3).cumsum())
new_df = groups.agg({'col1':'first', 'col2':'sum','col3':'sum'})
new_df['col4'] = groups['col1'].last()

暫無
暫無

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

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