Pandas: sum consecutive rows satisfying condition

mathology

I have a pandas data frame of the form

index value condition
0 11 False
1 12 True
2 13 True
3 14 False
4 15 True
5 16 True
6 17 True
7 18 False

My goal is to get all differences of the value of consecutive groups of rows satisfying the condition, i.e. in this example, I want to have a list [13 - 12, 17 - 15]. Is there an efficient way with pandas to do this?

Shubham Sharma

You can take cumsum on condition column to identify the blocks of rows satisfying the condition, then group the column value on these blocks and agg using numpy.ptp:

m = df['condition']
blocks = (~m).cumsum()[m]
lst = list(df['value'].groupby(blocks).agg(np.ptp))

Details:

>>> blocks

1    1
2    1
4    2
5    2
6    2
Name: condition, dtype: int64

>>> lst 

[1, 2]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how to get rows satisfying certain condition pandas

pandas df filter on rows with any n rows satisfying condition

Consecutive rows meeting a condition in pandas

Using Pandas to drop the extra rows after satisfying a condition

how to sum rows with condition? (pandas)

Pandas renaming all consecutive rows based on condition

Python Pandas: Search rows with consecutive condition

Consolidation of consecutive rows by condition with Python Pandas

Pandas combine consecutive rows based on condition

Sum of Maximum Postive and Negative Consecutive rows in pandas

Only sum pandas rows Consecutive when column has consecutive number

Delete rows satisfying condition for each column in R

Pandas: sum every N amount of rows by condition

Pandas sum rows by group based on condition

pandas dataframe - find longest consecutive rows with a certain condition

Select rows where 3 consecutive values match condition - Python, Pandas

Pandas find consecutive rows where following row meets condition

Pandas DataFrame: Remove row satisfying certain condition

How to get sum of k consecutive rows in pandas dataframe?

Sum consecutive rows' values between 2 conditions using pandas

Count consecutive condition in pandas

Slice consecutive rows pandas

Pandas get consecutive rows

Panda groupby: counting rows satisfying condition on other columns?

Select rows satisfying condition on two variables jointly in dplyr

R count and list unique rows for each column satisfying a condition

Retrieve rows satisfying any one condition or both conditions

How to easily create variable with number of group rows satisfying treatment condition?

SQL query to compare rows satisfying a time stamp condition