2017-09-06 350 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]