Creating aggregated column in SQL with values depending on previous row - MySQL 5

104 Views Asked by At

I would like to get some help on the following query: I have the following data frame I created with python pandas:

data = pd.DataFrame({'user_id':[1,1,1,2,2],'event':[1,0,1,1,0]})

The output is:

user_id event
 1      1
 1      0
 1      1
 2      1
 2      0

Now, I have created a third column in the following way: for every user_id group, if the previous value of event is 0, then write 1, else 0:

g = data.groupby('user_id')
data['third_column']=g['event_id'].transform(lambda x: np.where((x.shift(1)==0),1,0))

And I get

user_id event   third_column
 1      1       0
 1      0       0
 1      1       1
 2      1       0
 2      0       0

How can I reproduce the same output in MySQL 5?

Thanks for your help

0

There are 0 best solutions below