I have a pandas DataFrame that is generated by this snippet:
elig = pd.DataFrame({'memberid': [1,1,1,1,1,1,2],
'monthid': [201711, 201712, 201801, 201805, 201806, 201807, 201810]})
and I would like to perform a .groupby operation on memberid based on continuous values of monthid, e.g., I would like the (very) end result to be a table looking like this:
memberid | start_month | end_month
1 | 201711 | 201801
1 | 201805 | 201807
2 | 201810 | 201810
I was wondering whether there is an idiomatic Pandas way to do this. So far I have tried a convoluted method, defining a new_elig = defaultdict(list) and then an outside function:
def f(x):
global new_elig
new_elig[x.iloc[0]['memberid']].append(x.iloc[0]['monthid'])
and finally
elig.groupby('memberid')[['memberid', 'monthid']].apply(f)
which takes about 5 minutes for ~700k rows in the original DataFrame in order to create new_elig, which then I have to manually inspect for each memberid so as to get the continuous ranges.
Is there a better way? There has to be one :/