[英]how to print in single line with an inline if else statement in python 2.7
[英]Python groupby with single line if else statement
我想將單行 if else 語句應用於我的數據框中的組,但不確定如何映射它。
我的數據如下所示:
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'
我希望重疊是一個單一的值,如overlap_new 中所示,基於重疊中的值。
這是我的代碼:
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']])
如何將 groupby 應用於單個 if else 行?
使用GroupBy.transform
與測試值由Series.any
的比賽每團至少一個值:
f = lambda x: 'partial' if (x == 1).any() else 'complete' if (x == 2).any() else 'none'
sample['overlap_new'] = sample.groupby('user')['overlap'].transform(f)
print (sample)
user in out location overlap Time \
0 ron 12/21/2021 10:11 12/21/2016 17:50 home 0 4:19:03
1 ron 12/21/2016 13:26 12/21/2016 13:52 office 2 0:25:28
2 april 12/21/2016 8:12 12/21/2016 17:27 office 0 8:15:03
3 april 12/21/2016 18:54 12/21/2016 22:56 office 0 4:02:36
4 andy 12/21/2016 8:57 12/21/2016 12:15 home 0 2:59:40
5 andy 12/21/2016 8:57 12/21/2016 12:15 home 1 2:59:40
overlap_new
0 complete
1 complete
2 none
3 none
4 partial
5 partial
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.