簡體   English   中英

Pandas數據幀分組值

[英]Pandas dataframe grouping values

我有像這樣的熊貓數據框,

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

在此輸入圖像描述

我需要將seconds列合並為具有相同名稱的行的單個列表。

我能夠使用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,
})

輸出:

在此輸入圖像描述

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

謝謝!

使用groupbyapply list

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

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

使用groupbyaggtolist

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

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM