I have a Pandas dataframe that I'm grouping by two columns: ID and Item. I am then keeping the last 5 occurrences in each group (maximum), and would finally like to calculate a ratio of the number of occurrences of one specific type.Specifically, I would like to calculate the count of 'U' for each ID-item divided by the total number of occurrences.
I am having trouble with the last step - I am not sure how to get from the general value counts below to a ratio for each ID-Item grouping. Any tips would be much appreciated - thank you!
d={'ID':[1,1,1,1,1,2,2,2,2,2],'Item': ['box','box','ball','ball','box','box','box','ball','box','ball'],'Direction':['D','U','U','D','U','U','D','D','D','D']}
df=pd.DataFrame(data=d)
z=company_item['revision_arrow'].value_counts()
groups=df.groupby(['ID','Item'])
max_count=5
lastfive=groups.head(max_count).reset_index(drop=True)
#count_series=lastfive['Direction'].value_counts()
count_series=groups['Direction'].value_counts()