Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding time in location for each user: using the shift function

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
like image 894
kikee1222 Avatar asked Aug 23 '26 03:08

kikee1222


1 Answers

You may check groupby with diff

df.groupby(level=0).diff()
like image 167
BENY Avatar answered Aug 25 '26 16:08

BENY