lundi 23 mars 2020

Python groupby with single line if else statement

I would like to apply a single line if else statement to a group in my data frame, but unsure how to map it.

My data looks like this:

    user                in               out location  overlap    Time    overlap_new
0    ron  12/21/2021 10:11  12/21/2016 17:50     home     0  4:19:03      'complete'
1    ron  12/21/2016 13:26  12/21/2016 13:52   office     2  0:25:28      'complete'
2  april   12/21/2016 8:12  12/21/2016 17:27   office     0  8:15:03      'none'
3  april  12/21/2016 18:54  12/21/2016 22:56   office     0  4:02:36      'none'
4   andy   12/21/2016 8:57  12/21/2016 12:15     home     0  2:59:40      'partial'
5   andy   12/21/2016 8:57  12/21/2016 12:15     home     1  2:59:40      'partial'

I would like the overlap to be a single value as shown in overlap_new, based on the value in overlap.

Here is my code:

s = sample.groupby('user')['overlap']
sample.loc[:,'overlap_new'] = s.apply(['partial' if ele == 1 else 'complete' if ele ==2 else 'none' for ele in sample['overlap']])

How do I apply a groupby to a single if else line?

Aucun commentaire:

Enregistrer un commentaire