Creating a counter that increments when value is 1 in dataframe

Viewed 44

I have a dataframe similar to the one below.

            dry_bulb_tmp_mean       Time  Timedelta
Date                                               
2011-01-14         -11.245833 2011-01-14        NaN
2011-01-15         -12.608333 2011-01-15        1.0
2011-01-16         -15.700000 2011-01-16        1.0
2011-01-17         -19.954167 2011-01-17        1.0
2011-01-20         -13.654167 2011-01-20        3.0
2011-01-21         -11.887500 2011-01-21        1.0
2011-01-22         -17.866667 2011-01-22        1.0
2011-01-23         -23.250000 2011-01-23        1.0
2011-01-24         -23.654167 2011-01-24        1.0
2011-01-25         -16.254167 2011-01-25        1.0
2011-01-30         -12.233333 2011-01-30        5.0
2011-01-31         -19.041667 2011-01-31        1.0

I am tasked with creating a new dataframe that gives me the lengths for different runs. Basically, a run is however many consecutive days occur in the dataframe. For example, from the 14th, to the 17th I get a run of 4, but then at the 20th I get a run of 1. I have attempted to do this as follows.

            if temp_persis33['Timedelta'].iloc[row] == 1:
                length += 1

Every time a value greater than 1 is found in the Timedelta column, it will append the counter to a list, and then reset the counter. However, I am not sure how to compare the values in the dataframe. I have tried a few different things and nothing has worked. Any help would be appreciated, thank you.

2 Answers

IIUC try grouping on a boolean array where Timedelta does not equal 1

df.groupby(df['Timedelta'].ne(1).cumsum())['Time'].count().to_numpy()
# array([4, 6, 2])

You don't even need to create the Timedelta column. You can apply diff directly to it. pd.DataFrame.diff() works directly with datetime:

df.groupby(df.Time.diff().ne(1).cumsum()).Time.count()
Related