2016-08-11 76 views
2

我有數據幀熊貓:使用GROUPBY成一張桌子

i,Unnamed: 0,ID,active_seconds,subdomain,search_term,period,code,buy  
0,56574,08cd0141663315ce71e0121e3cd8d91f,6,market.yandex.ru,None,515,100.0,1.0 
1,56576,08cd0141663315ce71e0121e3cd8d91f,26,market.yandex.ru,None,515,100.0,1.0 
2,56578,08cd0141663315ce71e0121e3cd8d91f,14,market.yandex.ru,None,515,100.0,1.0 
3,56579,08cd0141663315ce71e0121e3cd8d91f,2,market.yandex.ru,None,515,100.0,1.0 
4,56581,08cd0141663315ce71e0121e3cd8d91f,8,market.yandex.ru,None,515,100.0,1.0 
5,56582,08cd0141663315ce71e0121e3cd8d91f,32,market.yandex.ru,None,515,100.0,1.0 
6,56583,08cd0141663315ce71e0121e3cd8d91f,16,market.yandex.ru,None,515,100.0,1.0 
7,56584,08cd0141663315ce71e0121e3cd8d91f,4,market.yandex.ru,None,515,100.0,1.0 
8,56585,08cd0141663315ce71e0121e3cd8d91f,10,market.yandex.ru,None,515,100.0,1.0 
9,56639,08cd0141663315ce71e0121e3cd8d91f,2,market.yandex.ru,None,516,100.0,1.0 

我想表的active_seconds金額和數量的period(壹號是一個週期)。在這種情況下,我想要獲取此ID的句點數= 2。 我用

df.groupby(['ID', 'buy']).agg({'period': len, 'active_seconds': sum}).rename(columns={'active_seconds': 'count_sec', 'period': 'sum_session'}).reset_index() 

但它返回uncorrectly值時期的數量。我該如何解決這個問題?使用替代

回答

1

'nunique'len

df.groupby(['ID', 'buy']).agg({'period': 'nunique', 'active_seconds': sum}) \ 
    .rename(columns={'active_seconds': 'count_sec', 'period': 'sum_session'}).reset_index() 

enter image description here