Create function to count number of web sessions in dataframe per unique ID

Viewed 44

I've got a dataframe structured in the following way:

timestamp participant id upstream downstream
1.1.2020 person 1 1 0
1.1.2020 person 1 1 1
1.2.2020 person 1 1 0
1.2.2020 person 1 1 1
1.1.2020 person 2 1 0
1.1.2020 person 2 1 1
1.2.2020 person 2 1 0

I'm looking to create a function which creates a cumulative count of sessions per person. A new session starts when upstream = 1 and downstream = 0.

The ideal output is this:

timestamp participant id session
1.1.2020 person 1 1
1.1.2020 person 1 1
1.2.2020 person 1 2
1.2.2020 person 1 2
1.1.2020 person 2 1
1.1.2020 person 2 1
1.1.2020 person 2 2

What I've attempted so far is;

    if (s['upstream']==1 and s['downstream']==1):
        return 1

But i'm unsure how to get this to give a cumulative count specific to each person. So when there is a new person identifier, the count restarts to 0.

Any help much appreciated, thanks a lot.

1 Answers

Try:

df["session"] = df["upstream"].eq(1) & df["downstream"].eq(0)
df["session"] = df.groupby("participant id", as_index=False)["session"].cumsum()
print(df)

Prints:

  timestamp participant id  upstream  downstream  session
0  1.1.2020       person 1         1           0        1
1  1.1.2020       person 1         1           1        1
2  1.2.2020       person 1         1           0        2
3  1.2.2020       person 1         1           1        2
4  1.1.2020       person 2         1           0        1
5  1.1.2020       person 2         1           1        1
6  1.2.2020       person 2         1           0        2
Related