I have a spatial and temporal df:
'date' 'spatial_pixel' 'column_A' ...
---- ----- ---
2012-04-01 | 1000 | 5
2012-04-01 | 1001 | 1
... ... ...
I want a column (groupedby 'spatial_pixel' and 'date') that counts the days-in-a-row a boolean is met. Say 'column_A' < 2:
'date' 'spatial_pixel' 'column_A' 'days-in-a-row' ...
---- ----- --- ----
2012-03-30 | 1001 | 5 | 0
2012-04-01 | 1001 | 1 | 1
2012-04-02 | 1001 | 1 | 2
2012-04-03 | 1001 | 3 | 0
... ... ... ...
My Attempts:
First, I made a new dataframe that when the boolean is True ('column_A'< 2) the monthly day number (e.g. 1,2,3,....28,29,30) is written. (However, I need it to range from 1-365, so that end of months and beginning of months are easily identified as consecutive).
'date' 'spatial_pixel' 'column_A' 'day' ...
---- ----- --- ----
2012-03-30 | 1001 | 5 | NaN
2012-04-01 | 1001 | 1 | 1
2012-04-02 | 1001 | 1 | 2
2012-04-03 | 1001 | 3 | NaN
2012-04-30 | 1001 | 1 | 30
2012-04-31 | 1001 | 1 | 31
... ... ... ...
Second,
I have unsuccessfully tried to create a new column that counts how many consecutive month days, using modified code from @ZJS: Pandas: conditional rolling count.
def rolling_count(val):
if val == rolling_count.previous + 1 :
rolling_count.count +=1
else:
rolling_count.previous = val
rolling_count.count = 1
return rolling_count.count
rolling_count.count = 0 #static variable
rolling_count.previous = None #static variable
df['count'] == df.groupby(['spatial_pixel','date'])['day'].apply(rolling_count)
KeyError: 'count'
Any help would be greatly appreciated!