2017-09-06 232 views
1

我有一個熊貓據幀像這樣,熊貓據幀分組值

dd = pd.DataFrame(
{'name': ['abc','bcd','abc'], 
'seconds': [75,77,90], 
}) 

enter image description here

我需要秒列合併爲同名行一個列表。

我能for循環做到這一點使用,

names= list(set(dd['name'])) 
counter=[] 
for a in names: 
    counter.append(list(dd[dd['name'] == a]['seconds'])) 
end 
seconds_list = pd.DataFrame(
{'name': names, 
'seconds': counter, 
}) 

輸出:

enter image description here

但是這需要花費大量的時間在一個大的數據幀。任何簡單的方法來實現這個沒有for循環?

謝謝!

回答

2

使用groupbyapplylist

df = dd.groupby('name')['seconds'].apply(list).reset_index() 
print (df) 

    name seconds 
0 abc [75, 90] 
1 bcd  [77] 
1

使用groupbyagg,並tolist

dd.groupby('name')['seconds'].agg(lambda x: x.tolist()).reset_index(name='seconds') 

輸出:

name seconds 
0 abc [75, 90] 
1 bcd  [77]