I am trying to identify the most probable event (transportation) of customers. This is an example df:
df = pd.DataFrame({'customer id':[1,1,1,2,2,2,2,2,2,2,3,3],
'Trans':['Car','Car','Bus','Bus','Bus','Bus','Car','Car','Car','Plane','Car','Bus']})
gives:
customer id Trans
0 1 Car
1 1 Car
2 1 Bus
3 2 Bus
4 2 Bus
5 2 Bus
6 2 Car
7 2 Car
8 2 Car
9 2 Plane
10 3 Car
11 3 Bus
I did the following steps to get the largest probable values for each customer id:
#Get the count & percent of each customer id transportation
df2 = df.groupby(['customer id','Trans'])['Trans'].size().reset_index(name='Trans Counts')
df2['percent'] = df2.groupby("customer id")['Trans Counts'].transform(lambda x: (x / x.sum()).round(2))
#Get records > 1
df3 = df2[df2['Trans Counts'] > 1]
So I got this df:
customer id Trans Trans Counts percent
1 1 Car 2 0.67
2 2 Bus 3 0.43
3 2 Car 3 0.43
There is a tie for customer id 2, so when I use idxmax() :
df3.loc[df3.groupby('customer id')['Trans Counts'].idxmax()]
It only shows the first row:
customer id Trans Trans Counts percent
1 1 Car 2 0.67
2 2 Bus 3 0.43
How can I get the top 2 records within the same group in case of a tie? I also used try nlargest(2) but I got the results for the whole df not within the grouping & if I used it within the aggregate function, it does not show the expected output!
Expected output in case of a tie:
customer id Trans Trans Counts percent
1 1 Car 2 0.67
2 2 **Bus, Car** 3 0.43
Thanks