I am looking at the below to work out the amount of time each user spends in each location.
It's working great, but the problem is the line that shows -4.0. This is a new user & it's the first country they've been identified in - until I see them move countries, I can't calculate the length of time that they've been in that location.
For the first location of each user, I need the result to be set to NaN as it is for user 1.
Is this possible?
df2['time_in_loc'] = df2['hour'] - df2['hour'].shift(1)
In [36]: df2
Out[36]:
hour hop time_in_loc
userid country
82718927392 UK 0 1 NaN
Spain 2 2 2.0
Portugal 4 3 2.0
47294872934 India 0 1 -4.0
UK 15 2 15.0
You may check groupby with diff
df.groupby(level=0).diff()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With