I have some code like so in pandas to get the number of times a person switches restaurants:
Data Extract:
Date PersonId RestaurantName
01/01/2021 12 McDonalds
01/02/2021 12 McDonalds
01/02/2021 12 Wendys
01/03/2021 12 Popeyes
01/01/2021 14 Popeyes
01/02/2021 14 McDonalds
01/02/2021 14 Wendys
01/02/2021 14 Popeyes
Code that is too slow:
df['SwitchCount'] = df.groupby('PersonId')['RestaurantName'].transform(lambda x: x.shift().ne(x).sum()-1)
How can I optimize this code? My understanding is that transform is very computationally expensive. how can I change this code to be faster but do the same logic?o